Its a difficult business to avoid closing the browser window. In fact, there is no way to do this other than returning an undefined
value from the onbeforeunload
event, as you described.
There is one possible suggestion that I can make is to create a synchronized ajax request in the onbeforeunload
event. For example,
window.onbeforeunload = function() { $.ajax({ url: '/foo', type: 'GET', async: false, timeout: 4000 }); };
In theory, this blocks the browser for a maximum of 4 seconds. In fact, browsers will treat this differently. For example, Firefox (I checked it for 9) doesn’t really close the window right away, but it also doesn’t respect the timeout value. I assume that there is an internal maximum, like 2 seconds before the request is canceled, and the window / tab closes. However, in most cases this should be enough.
Your other question (how to distinguish a click on a link) is quite simple. As described above, onbeforeunload
looks to be returned from event handlers. So let's assume that we have a global variable for our application, we could do something like
var globalIndicator = true; // ... lots of code window.onbeforeunload = function() { return globalIndicator; };
At this point, we will always receive a confirmation dialog when the window / tab is closed. If we want to avoid this for any click of the anchor, we can fix it as
$( 'a[href^=http]' ).on('click', function() { globalIndicator = undefined; });
jAndy
source share