且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序:chrome.alarms在主窗口关闭后无法正常工作

更新时间:2023-12-05 18:46:58

仅当用户配置文件的至少一个浏览器窗口正在运行时,扩展才运行,除非您专门添加了

I want to check a certain value in my extension every few hours using the chrome.alarms API. The alarms are triggering while the main window page is open, but when the main window closes the alarms no longer trigger. My event listener and alarm creation are on the background page. In my background.js, I try to make a notification appear at a regular interval to test the alarm.

This is the relevant part of my "background.js":

document.addEventListener("DOMContentLoaded", function(e) {

  chrome.runtime.getBackgroundPage(function(bg) {
      bg.chrome.alarms.create("beep", {delayInMinutes: 1, periodInMinutes: 0.1} );
  });

  var opt = {
    type: "basic",
    title: "Task due",
    message: 'A task is due tomorrow.',
    iconUrl: "chrome-extension://paomcbcgpoikdcjhbanhllhdbemcjokf/Agenda_32.png",
    buttons: [
      {
      title: 'Mark as done'
      }
    ]
  }
  

  function clr() {
    chrome.notifications.clear('tst');
  }
  
  chrome.alarms.onAlarm.addListener(function(alarm) {
    console.log("beeep");
    clr();
    chrome.notifications.create('tst', opt);
  });
});

How can I make it so that the alarms trigger even after my main window closes? I have read some documentation on this but the solution to this eludes me.

Extensions run only when at least one browser window of the user profile is running unless you specifically add a permission in manifest.json:

"permissions": ["background"],
"background": {
  "persistent": true,
  "scripts": ["bg.js"]
}

Makes Chrome start up early and and shut down late, so that apps and extensions can have a longer life.

When any installed hosted app, packaged app, or extension has "background" permission, Chrome runs (invisibly) as soon as the user logs into their computer—before the user launches Chrome. The "background" permission also makes Chrome continue running (even after its last window is closed) until the user explicitly quits Chrome.

Important!

Make sure Continue running background apps is enabled in Chrome settings: