It is not possible for the Chrome extension to run some code reliably when you close the browser.
Instead of clearing after shutdown, just make sure that old alarms do not start at startup. This can be achieved by creating a unique (for the session) identifier.
If you use event pages, save the identifier in chrome.storage.local (remember to set the storage permission in the manifest file). Otherwise, save it in the global area.
// ID generation: chrome.runtime.onStartup.addListener(function () { console.log('Extension started up...'); chrome.storage.local.set({ alarm_suffix: Date.now() }, function() { // Initialize your extension, eg 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 use not , using event pages, but regular background pages, just save the variable globally (advantage: read / write id 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);
Rob w source share