传统定时器(setTimeout,setInterval)在backgroun.js里无效
解决办法
使用chrome插件新api-[alarms]
参数解释
periodInMinutes----相当于setInterval,每隔多少分钟执行一次
delayInMinutes----相当于setTimeout,多少分钟后执行
when----传入时间戳,相当于闹钟,当到达这个时间的时候执行
示例
//创建一个警报
chrome.alarms.create("stm", { periodInMinutes: 1 });
chrome.alarms.onAlarm.addListener(() => {
let index = 1
chrome.storage.local.get(["index"], function (result) {
if (result.index) {
index = result.index
index++
chrome.storage.local.set({ 'index': index })
console.log("执行次数:" + index)
if (index == 2) {
//清除警报
chrome.alarms.clear("stm")
}
} else {
//首次执行
chrome.storage.local.set({ 'index': index })
console.log("首次执行")
}
})
});
注意事项
1.使用时需要在manifest.json里注册权限[alarms]
2.alarms最小时间限制在1分钟,也就是说参数只能大于等于1分钟,小于1分钟则会报错
3.alarms使用时需要定义一个name,如果不定义name直接使用的话,第二个alarms会覆盖第一个