Tag Archives: onbeforeunload

Catching the Javascript beforeunload event, the cross-browser way

Javascript’s window.onbeforeunload event is useful for catching users that try to browse away from your page without having completed a certain action. Modern web applications such as Gmail and WordPress have made good use of this event.

Being a non-standard event originally invented by Microsoft back in the IE4 days, window.onbeforeunload has some real quirks, although thankfully every major modern browser does support it.

jQuery Doesn’t Help

Prior to jQuery 4, you couldn’t even bind to $(window).bind('beforeunload') due to a bug that has been fixed.

However, this isn’t your average Javascript event. window.onbeforeunload pops up a native dialog box that provides very little opportunity for customization beyond the text that is displayed to the user. There is no known way to disable this native dialog box and prevent normal behavior.

Tapping into jQuery’s $(window).unload() event doesn’t allow you to prevent the page from being unloaded, and I couldn’t get $(window).bind('beforeunload') to work at all in Firefox 3.6.

The Right Way

The right way turned out to be quite easy using native Javascript code (thanks to the Mozilla Doc Center for the working solution).

For IE and FF < 4, set window.event.returnValue to the string you wish to display, and then return it for Safari (use null instead to allow normal behavior):

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Any string';
    }

    // For Safari
    return 'Any string';
};