Chrome Extension Alarms go off when Chrome is reopened after time runs out?

牧云@^-^@ 提交于 2019-12-03 16:49:37

It's not possible for a Chrome extension to reliably run some code when the browser closes.

Instead of cleaning up on shutdown, just make sure that old alarms are not run on startup. This can be achieved by generating an unique (to the session) identifier.

If you're using event pages, store the identifier in chrome.storage.local (don't forget to set the storage permission in the manifest file). Otherwise, store it in the global scope.

// ID generation:
chrome.runtime.onStartup.addListener(function () {
    console.log('Extension started up...');
    chrome.storage.local.set({
        alarm_suffix: Date.now()
    }, function() {
        // Initialize your extension, e.g. create browser action handler
        // and bind alarm listener
        doSomething();
    });
});

// Alarm setter:
chrome.storage.local.get('alarm_suffix', function(items) {
    chrome.alarms.create('myAlarm' + items.alarm_suffix, {
        delayInMinutes : 2.0
    });
});

// Bind alarm listener. Note: this must happen *after* the unique ID has been set
chrome.alarms.onAlarm.addListener(function(alarm) {
    var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
    if (parsedName) {
        alarm.name = parsedName[0];
        alarm.suffix = +parsedName[1];
    }
    if (alarm.name == 'myAlarm') {
        chrome.storage.local.get('alarm_suffix', function(data) {
            if (data.alarm_suffix === alarm.suffix) {
                doSomething();
            }
        });
    }
});

If you're not using event pages, but normal background pages, just store the variable globally (advantage: id reading/writing becomes synchronous, which requires less code):

chrome.runtime.onStartup.addListener(function () {
    window.alarm_suffix = Date.now();
});
chrome.alarms.create('myAlarm' + window.alarm_suffix, {
    delayInMinutes : 2.0
});
chrome.alarms.onAlarm.addListener(function(alarm) {
    var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
    if (parsedName) {
        alarm.name = parsedName[0];
        alarm.suffix = +parsedName[1];
    }
    if (alarm.name == 'myAlarm') {
        if (alarm.suffix === window.alarm_suffix) {
            doSomething();
        }
    }
});

Or just use the good old setTimeout to achieve the same goal without side effects.

setTimeout(function() {
    doSomething();
}, 2*60*1000); // 2 minutes
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!