Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Background Script Unload

For my chrome and firefox extension, I need a way to figure if the background script has unloaded or is unloading. Is there an event fired when this happens? I went through multiple links on stackoverflow and even some official chromium bug links but could not find a concrete answer. beforeunload is not supported for background scripts and closing the windows does not guarantee that browser is closed cause if extension has "background" permission, the background script would still be running in background. What can I do now?

like image 513
discoverAnkit Avatar asked Apr 13 '16 10:04

discoverAnkit


People also ask

What does background script do in Chrome extension?

Background script can react to browser events and perform certain actions, the background page is loaded when it is needed, and unloaded when it goes idle. To use the background file, declare it as follows in the manifest.

What is a background script?

Background scripts are the place to put code that needs to maintain long-term state, or perform long-term operations, independently of the lifetime of any particular web pages or browser windows.


1 Answers

The closest there is is chrome.runtime.onSuspend, but there is no guarantee how much time you're allowed before the context shuts down. Note that this is not supported in WebExtensions as of yet. The documentation expressly states:

Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete.

In general, you can't do much on event/background page unload and should make your code robust to abrupt unloads. This event may even not trigger for some shutdowns.

like image 95
Xan Avatar answered Oct 06 '22 00:10

Xan