Event onBrowserClose for Google Chrome Extension?

I am developing an extension for Google Chrome. My background script, everytime, authorizes on a server that uses the XMPP API, and subscribes for a PubSub node. I need to unsubscribe on the exit, otherwise the dummy subscriptions will remain on the server. Is There any onBrowserClose event in the Google Chrome Extension APIs?



There is no such event in the Chrome Extension API.

There is however a chrome.windows.onRemoved event that fires each time a window closes. I figured you could check in this event if you closed the last window, but unfortunately due to the asynchronous nature of Chrome this doesn't work.

What I tried was running a simple AJAX request in the onRemoved event handler. The AJAX request never got to the server, as Chrome had already closed before running the event (or just disregarded it).

Making the final answer be: No, currently you can't, as far as I know. You might want to star the following bug report at http://crbug.com/30885 to get noticed on updates.


If you catch the case when the number of open tabs is 0, you can treat that as a Chrome onClose event. In my case, I have to cancel a desktop notification before Chrome closes because it was crashing otherwise. This is how I did it:

1. Initialize a variable num_tabs by using the following:
chrome.tabs.getAllInWindow( null, function( tabs ){
    console.log("Initial tab count: " + tabs.length);
    num_tabs = tabs.length;
2. Increment num_tabs when a tab is created:
    console.log("Tab created event caught. Open tabs #: " + num_tabs);
3. Decrement num_tabs when a tab is removed and run your browser onclose event handler if num_tabs = 0
    console.log("Tab removed event caught. Open tabs #: " + num_tabs);
    if( num_tabs == 0 )

This one works for me:

  alert("!! Exiting the Browser !!");

It takes chrome.windows rather than chrome.tabs.


Adding a browser close event is a pretty frequent request. Star http://crbug.com/30885 for updates. And read the bug report for a clever hack to detect when the browser is shut down via a key press.


TL;DR: Try window.onunload event, it works for some cases.

As it was mentioned before we generally can't handle something like onBrowserClose event and prevent browser from closing. But for some cases we can use window.onunload event for doing something synchronously, and it does work if it really synchronously.

From my experience you can at least:

  • Save some information in (for example logs) in HTML5 localStorage (which is synchronous).
  • Call some asynchronous chrome extension API functions but you can't get a result. (It works for me! Yay!)
  • Perform synchronous XMLHTTPRequest (yeah, sometimes it works).


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.