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';
};

9 thoughts on “Catching the Javascript beforeunload event, the cross-browser way”

  1. hello, I’m spanish. I’m trying cancel de beforeunload event. I like open the thickbox with a text, and depend off de option, continue in this page or in other page.

    window.onbeforeunload = function(Event)
    {
    console.log(Event);

    Event.defaultPrevented();
    Event.stopImmediatePropagation()
    Event.stopPropagation();

    //open thickbox

    }

    Thanks

  2. Try this:

    window.onbeforeunload = function(Event)
    {
    console.log(Event);
    
    Event.preventDefault();
    Event.stopImmediatePropagation();
    Event.stopPropagation();
    
    //open thickbox
    
    }
  3. Hi Jonathon, Very Good Morning..

    I got a small problem when handling the Unbeforeload.
    My Problem: Based on Some count i need to show a pop-up and if the count equals. I need to cancel the pop-Up.. Can i handle “X” button in Pop_Up window. If the user clicks on it, is it possible to show any error Message?

    Thanks,
    Samsi.

  4. i need to make update the logged user status in db when i close the browser ‘X’ button the following code is working in else block only but if block is not executed? i need solution help….code is as follows

    $(window).bind(‘unload’, function(){
    operaBrowserclose(”);
    });

    function operaBrowserclose(user) {
    //alert(user)
    alert(posX+’ ‘+posY)
    if(posY<=20)
    {
    alert("in if "+posX+' '+posY)
    return "jaga"
    //newWindow=window.open('http://192.168.0.26/24hours_movies?logout=logout&#039;);
    //newWindow.focus();
    alert('browser is closed');
    }
    }

    window.onbeforeunload = function(){
    $(window).unbind('unload');
    return 'beforeunload event';
    }

    document.onmousemove = function(evt) {
    if (typeof evt == 'undefined') {
    myEvent = window.event;
    } else {
    myEvent = evt;
    }
    if(myEvent.clientX){
    posX = myEvent.clientX+document.body.scrollLeft;
    posY = myEvent.clientY+document.body.scrollTop;//alert(posY)
    }
    else if(myEvent.pageX){
    posX = myEvent.pageX+window.pageXOffset;
    posY = myEvent.pageY+window.pageYOffset;
    }
    }

  5. Thanks for the article! Is there anything wrong with this simplified code:
    window.onbeforeunload = function () {
    return 'You have unsaved changes!';
    };

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>