The official documentation says this about alarms persistence:
Alarms generally persist until an extension is updated. However, this is not guaranteed, and alarms may be cleared when the browser is restarted. Consequently, consider setting a value in storage when an alarm is created, and then ensure it exists each time your service worker starts up.
What I find missing is a way to assure the worker actually starts up in case the alarms get cleared. Is there a recommended event which the worker should register for (other than the alarm event) in order to assure it gets started to re-create the alarm?
Normally, onInstalled and onStartup (when the browser loads your user profile at startup) events should suffice to check the alarm and recreate it if there was none.
// Not checking `reason` as we want to run this both when the extension
// was installed/updated or the browser was updated.
chrome.runtime.onInstalled.addListener(initAlarms);
chrome.runtime.onStartup.addListener(initAlarms);
function initAlarms() {
chrome.alarms.get('foo', alarm =>
if (!alarm) chrome.alarms.create('foo', { periodInMinutes: 60 });
});
}
The documentation suggests doing it every time the service worker wakes up regardless of the cause i.e. just call initAlarms()
instead of using chrome
events, which isn't a bad idea in this case since the check is simple.