简体   繁体   中英

chrome extension: when does a persistent background script stop running?

If my chrome extension has a persistent background script, I could use it to store data in the script that I would eventually want to store in chrome.storage.local. When / what event triggers the background script to stop running (so that I can add a callback to store the data in chrome.storage.local before the local data goes out of scope)?

Background scripts can either be registered persistent (always running while the extension is enabled and has not crashed) or non-persistent (not always but temporarily runs when runtime.getBackgroundPage or any runtime event callback registerd in the background script is invoked)

They are registered in the manifest under the "background" field, and "persistent" should be specified as false for non-persistent background scripts/pages.

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

There is a runtime event callback for when the non-persistent background script is unloaded (because they unload on their own after a few seconds of inactivity), it does not get invoked when an extension with persistent background script is disabled (or crashed of-course).

chrome.runtime.onSuspend.addListener(function() {
    console.log("Unloading.");
});

You can verify that with this simple extension:

manifest.json

{
  "name": "onSuspend",
  "description": "onsuspent",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": [
    "storage"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  }
}

background.js

chrome.runtime.onSuspend.addListener(function() {
  console.log("Unloading.");
  chrome.storage.local.set({"Saved": "yes"}, function() {});
});

chrome.storage.local.get("Saved", function(data) {
  console.log("shouldn't be an empty object": data);
});

The only way I found that you can register a callback to run before the persistent background script is disabled is by loading a background page instead and using the window's unload event, code use for testing:

{
  "name": "callback before stopping persistent background script",
  "description": "callback before stopping persistent background script",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": [
    "storage"
  ],
  "background": {
    "page": "background.html",
    "persistent": true
  }
}

background.js

window.addEventListener('unload', function(event) {
  localStorage.setItem("Saved", "yes");
});
console.log("Saved:", localStorage.getItem('Saved'));

background.html

<html><body></body><script src="background.js"></script></html>

To test it try disabling and re-enabling or reloading the extension twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM