0

I wrote a simple Chrome Extension that pulls a string (price) from my webserver, every few seconds. When I install Chrome Extension, it works great. To achieve this I use this line in manifest.json:

"background": {
    "service_worker": "loadPriceInterval.js"
},

In that .js file I have setInterval function which is triggered every 10 seconds. It pulls new price and displays it as badge text, that's all. The problem happens when I close Chrome and run it again few hours later. My extension is still visible but price isn't updated. It looks like the extension won't pull new price. Seems like the extension is not loading loadPriceInterval.js and this few lines I have in loadPriceInterval.js:

(function() {

    setInterval(function() {
        readPriceFun();
    }, 9000); // 9 seconds

})();

How do I make sure extension would continue with this setInterval thing whenever Chrome is restarted, not only when I add extension?

Tioman Island
  • 91
  • 1
  • 1
  • 5
  • 2
    You need to add a listener for a [chrome API](https://developer.chrome.com/docs/extensions/reference/) event e.g. chrome.alarms, but it can only wake up every 1 minute, not 9 seconds. See also [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Apr 02 '23 at 14:54
  • You are right. I added chrome.alarm event to trigger every minute and extension will stay alive. Then I have setInterval in the code which is triggered every 10 seconds and everything works well. Even after I restart Chrome, the extension will be running. Thanks. – Tioman Island Apr 03 '23 at 19:47

0 Answers0