Question

I am playing with chrome extensions, my manifest loads a background page with:

...
"background": { "scripts": ["background_page.js"], "persistent": false },
...

The .js code looks like this:

var once = false;
window.addEventListener("load", function () {
  if ( once == true ) { return; }
  alert( 'test' );
  once = true;
}, false);

This seems to works fine, but i want to run the background_page.js code only once every time the browser starts.

Right now, I am not sure why, but the code is executed more than once. At first I thought it was being executed every time I open a new tab but that's not the case. The alert does appear once I start the browser, then if I open a new tab quickly the alert wont appear, but if I wait about 1 minute or so and open a new tab then the alert appears again.

How can i make sure the background_page.js code runs only once every time the browser starts?

Was it helpful?

Solution

What you are using is an Event Page(background_page.js). Event pages are unloaded when the browser detects that the page is not doing anything. So what's happening is that when you open a new tab, the Event page is being reloaded and starts executing from the top again. This way chrome is able to have your app use less memory and speed up the browser.

If you want to fix the problem simply use persistent:true which will make sure the page "persists" indefinitely or until the user closes the browser. If you would really like to keep your app efficient with memory, you should take a look at the runtime.onSuspend method which gets called each time your Event page unloads. This way you can save stuff before the page gets unloaded so that you can resume where you left off.

OTHER TIPS

UPDATE: According to current documentation you simply have to delete the persistent key (no need to change it to "persistent": true).

This is an event page:

{
  "name": "My extension",
  ...
  "background": {
    "scripts": ["eventPage.js"],
    "persistent": false
  },
  ...
}

This is a background page:

{
  "name": "My extension",
  ...
  "background": {
    "scripts": ["background.js"]
  },
  ...
}

To expand on quackkkk's answer, omitting the "persistent" key in the manifest.json is the same as setting it to "persistent": true

The proof:

In the docs, it says that:

The only occasion to keep a background script persistently active is if the extension uses chrome.webRequest API to block or modify network requests. The webRequest API is incompatible with non-persistent background pages.

with that in mind, we can check out the manifest.json one of the extension sample projects, No Cookies, that uses the webRequest API and see that it does not explicitly set "persistent"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top