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?
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.
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.
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.
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