使用Google Chrome瀏覽器擴展程序警報時,如果警報設置並且Chrome在警報的時間到期後關閉並重新打開,則該警報將關閉。當Chrome瀏覽器在時間用完之後重新打開時,Chrome擴展程序警報會關閉?
我該如何解決這個問題?
這裏是一個小代碼示例來解釋我的意思。
/*
If we perform Browser Action to create alarm, then
close the browser, wait about 2 minutes for the alarm to expire
and then reopen the browser, the alarm will go off and the DoSomething
function will get called twice, once by the onStartup event and once
by the onAlarm event.
*/
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.alarms.create('myAlarm', {
delayInMinutes : 2.0
});
});
chrome.alarms.onAlarm.addListener(function (alarm) {
console.log('Fired alarm!');
if (alarm.name == 'myAlarm') {
createListener();
}
});
chrome.runtime.onStartup.addListener(function() {
console.log('Extension started up...');
DoSomething();
});
function DoSomething() {
alert('Function executed!');
}
所以,如果你會在我的代碼示例頂部閱讀評論,您將看看會發生什麼。
我想要的是,如果瀏覽器關閉,警報就會被清除,因爲我希望DoSomething函數只在onStartup事件中執行,如果瀏覽器剛剛啓動,並讓警報執行DoSomething函數只有在瀏覽器啓動後,我的代碼纔會創建新的警報。
在瀏覽器關閉後,我不希望報警留在周圍,然後在瀏覽器重新打開時執行onAlarm。
這怎麼能實現呢?
data.alarm_suffix === alarm.suffix是不正確的,因爲報警被以比onStartup事件熄滅不同的時間創建的。(只有幾毫秒)。 – user1876122
@ user1876122因此,前述評論「//綁定警報監聽器。注意:這必須發生在*唯一的ID被設置後。 –