I am developing a browser extension for a real-time product. I have a background page with "persistent : true" set in the manifest.json (I am using version v2). I am continually polling the server for new data every second using setInterval(). The background script also caches the data it has gathered till present and gives it to any newly opened tab.
Things work fine until sometimes I noticed that when I put the computer to sleep for a long period, my poll to server just stops! If I refreshed any of the existing tabs, I do see cached data. This means, that the background page was not killed by Chrome. My question is, why is chrome just stopping the setInterval() call? Also, what is the correct way to revive the poll if it's stopped for some reason?
//relevant part of manifest.json
"background": {
"scripts": [
"js/background/jquery.min.js",
"js/background/bgconfig.js",
"js/background/backgroundmanager.js",
"js/background/eventsfetcher.js"
],
"persistent": true
},
Thanks!
According to the chrome documentation you should use the alarms API instead. I don't know if it will solve the issue but it's definitively worth trying!
I quote:
If your extension uses window.setTimeout() or window.setInterval(), switch to using the alarms API instead. DOM-based timers won't be honoured if the event page shuts down.
https://web.archive.org/web/20130715023501/http://developer.chrome.com/extensions/event_pages.html
=> https://developer.chrome.com/docs/extensions/reference/alarms/
For anyone else looking for the solution, I ended up implementing what @Pluto suggested :
"Store the intervalID returned from setInterval in a global variable, then when the window gains focus again, clear that interval and run setInterval again"
This has worked well for me so far with no dropped events from server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With