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?
Detect Background Script Unload
Asked Answered
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.
chrome.runtime.onSuspend is for event pages and I am not using that. I am using a persistent one. Lets consider a situation. There is some data in-memory pertaining extension and user shuts down chrome in any of the possible ways. Now, before chrome is actually shut down I want to save that data to local storage, how can I do that? –
Mosasaur
You basically can't. There is no event that the browser will wait for before shutting down. You should dump the data into the storage on a regular basis to have an up-to-date snapshot. –
Zorazorah
Yes but then about the edge case. The last piece of data which could not be dumped because the interval had not elapsed and chrome was already shut down. I guess you will now suggest having an interval as small as 1 sec? –
Mosasaur
No, I would suggest queueing a
storage.set
when your data changes. And be tolerant of loss of small chunk of data anyway since, again, no operation is guaranteed to finish before shutdown. –
Zorazorah The best Chrome's got is chrome.tabs.onRemoved –
Greenwald
© 2022 - 2024 — McMap. All rights reserved.