Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInteval in background script

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!

like image 568
Trunal Bhanse Avatar asked Sep 17 '25 03:09

Trunal Bhanse


2 Answers

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/

like image 139
Aegis Avatar answered Sep 19 '25 16:09

Aegis


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.

like image 40
Trunal Bhanse Avatar answered Sep 19 '25 16:09

Trunal Bhanse