I'm just making a simple chrome extension.
I want my background page(or part of ) to execute every 5 minutes, to get some data and display a desktop notification if any.How can I do this
I'm just making a simple chrome extension.
I want my background page(or part of ) to execute every 5 minutes, to get some data and display a desktop notification if any.How can I do this
Share Improve this question asked Dec 13, 2011 at 13:56 Li SongLi Song 6692 gold badges6 silver badges12 bronze badges 1- howtocreate.co.uk/tutorials/javascript/timers – CloudyMarble Commented Dec 13, 2011 at 14:02
2 Answers
Reset to default 31Important note: if you use a non-persistent background script (ManifestV3 service_worker
or ManifestV2 Event page with "persistent": false
in manifest.json), setInterval
with a 5-minute interval will likely fail as the background script will get unloaded after the idle timeout (30 seconds) unless you were lucky to have your other chrome
event listeners fire in-between or you intentionally kept the background script alive (MV3, MV2).
If your extension uses window.setTimeout() or window.setInterval(), switch to using the alarms API instead. DOM-based timers won't be honored if the event page shuts down.
In this case, you need to implement it using the chrome.alarms
API:
chrome.alarms.create("5min", {
delayInMinutes: 5,
periodInMinutes: 5
});
// To ensure a non-persistent script wakes up, call this code at its start synchronously
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name === "5min") {
doStuff();
}
});
In case of persistent background pages, setInterval
is still an acceptable solution. It should also work for short (on a scale of seconds, not minutes) intervals in a non-persistent script if you ensure the end is within the remainder of the idle timeout, see the above note.
One way to accomplish this would be:
setInterval(your_function, 5 * 60 * 1000)
Which would execute your_function
every 5 minutes (5 * 60 * 1000 milliseconds = 5 minutes)