The background.js mechanism was removed in manifest v3 and I'm looking for how one does periodic operations in the background now that it's gone.
This upgrade guide says to use the chrome alarm api: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/
Specifically it says:
Instead, we can use the Alarms API. Like other listeners, alarm listeners should be registered in the top level of your script.
It's not clear which script it needs to be the top level of, but when using the entry point of my chrome extension, "popup.js" it does periodically execute, but only when the chrome popup is actually open. I need it to execute in the background even when the popup is closed. A side note is that I get undefined for chrome.alarms until I add "alarms" to permissions in the manifest file and then it doesn't choke, but I still have the problem of it not running the background.
Since the above article is in the context of a service worker, I assume you instead need to put the alarm listener at the top level of the service-worker.js file. Only this doesn't work. I get undefined for chrome.alarms here (even with the "alarms" permission granted):
service-worker.js
console.log("inside service worker")
// getting chrome.alarms undefined here
chrome.alarms.create("alarm", { periodInMinutes: 1 });
Putting it in the install event listener doesn't help either:
self.addEventListener('install', event => {
console.log("Installing service worker")
// still getting chrome.alarms undefined here
chrome.alarms.create("alarm", { periodInMinutes: 1 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "alarm") {
let milliseconds = new Date().getTime();
console.log(milliseconds)
chrome.action.setTitle({
title: "Hello "+ milliseconds
});
}
});
});
Out of desperation I added the "background" permission to the manifest as well, but that didn't help either.
Any clue how to run something periodically in the background in manifest v3? Seems like the alarms api should be how you do it, but it's apparently inaccessible from a service worker?