chrome extension, execute every x minutes

2020-07-09 09:45发布

问题:

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

回答1:

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)



回答2:

Important note: if you make an extension with an Event page ("persistent": false in the manifest), setInterval with 5-minute interval will fail as the background page will get unloaded.

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
});

chrome.alarms.onAlarm.addListener(function(alarm) {
  if (alarm.name === "5min") {
    doStuff();
  }
});

In case of persistent background pages, setInterval is still an acceptable solution.