This post shows you how to bind JavaScript functions that will fire when user navigates away from your page, closes browser or a tab. Browsers have native JavaScript events on window object: unload
and beforeunload
. beforeunload
is a proprietary event introduced by Microsoft and supported by other browsers, but not all.
Please note, these events will be fired when user navigates away from the current page. This includes when user:
- closes the browser or a tab;
- clicks on any link (does not matter if it's to other domain or the current domain);
- types any URL to the browser bar and leaves the page;
- clicks browser's page reload, back, forward buttons.
NOTE
You must test your code, because the behavior of how browsers handleunload
event has changed even in different versions of the browsers.
Catching browser/tab close event with JavaScript
Since unload
is a native JavaScript event, we can get away without using jQuery at all.
window.onunload = function(){ // do some clean up clearLocalStorage(); };
If you are using alert()
, confirm()
or making AJAX requests here, please see what browsers block them belove.
Subscribing to browser/tab close using jQuery
jQuery introduced $.unload() event shorthand in v1.0 and deprecated it in v1.8. $.unload() is a shorthand for .bind('unload', handler).
$(window).unload(function() { // Do some code clean up });
How browsers handle alert(), confirm() and AJAX requests on unload event?
The document unload event was originally designed to let JavaScript to do some clean up. For example, clear or set cookies, but most of the time it is used to fire alert/confirm box or make an AJAX request to the server. This led to bad user experience and browsers started to block these methods in unload event.
Here is what each browser does:
- Chromer/Safari (WebKit)
alert()
,confirm()
- blocked (confirm()
returns false), AJAX request - not sent.
- Firefox
alert()
,confirm()
- blocked (throws an internalNS_ERROR_NOT_AVAILABLE
exception), AJAX requests - sent on page reload, but not on tab close.
- IE9
alert()
,confirm()
- not blocked, AJAX requests - not sent.
- Opera
alert()
,confirm()
- blocked, AJAX requests - not sent.
Browsers that have pop-up window blockers will block all
window.open()
function calls in unload event handler.