A way to detect that browser is closing

I’ve done some research and determined that there is no way to detect when browser is closing. And my question is why? Are there certain reasons or browser developers just think it’s not important API?
I’ve seen windows.onRemoved that not calls on last window, and some other ugly workarounds that are not working.
My extension should do all useful stuff before closing browser. The extension pointless without this. And this cannot be done when browser is launched or at any other point in time. Only before closing.
I’m very sad about this situation, and really don’t understand why such API isn’t provided.

Deep in my heart, I hope that there is still a solution. I don’t want to abandon the extension just because of this.

Native messaging with a Python script using https://docs.python.org/3/library/atexit.html

I haven’t tried this myself but it might work :slight_smile:

Thank you for your response.
But I don’t understand how native messaging with python script can help me detect browser closing and do something with browser extension API.

1 Like

For Chrome there is some runtime API:

I think you will have to wait for this one (maybe create bugzilla bug for it).

The problem with browser.windows.onRemoved or even browser.tabs.onRemoved can be also when user clicks the “Exit” button from the main menu, then all windows and tabs are closed together.

The only solution I can think of is to try to register beforeunload on the background script window object. But even if it works, I don’t think you will be able to execute any async operations.

But even if it works, I don’t think you will be able to execute any async operations.

onclosebrowser.zip (4.3 KB)

With the browser.windows.onRemoved method, browser.notifications.create doesn’t show a notification when you close the last window.

I’m using web-ext to run the extension.
Can I redirect the console messages to the terminal where I started web-ext?

@rob may know if you can output to web-ext.

But if you want verify that your code was executed, you can use instead of temporary web-ext profile a normal profile and write your log to window.localStorage because it’s synchronous. Then start the profile again and check the storage.

As far as I know there is no such event because there are no execution guarantees that can be made. Essentially extensions aren’t allowed to block shutdown or closing of a window/tab by design.

1 Like