Search code examples
jqueryonbeforeunload

Beforeunload event not working as I think it should


I want a user to be presented with a message when he tries to leave my page. My page consists of a form and some links (menu's etc). My jQuery code is the following

$(document).ready(function(){
    $(window).bind('beforeunload', function(e){
        answer=confirm('Do you want to go?');
        if (answer===false){
            e.preventDefault();
        }
    });
});

But when I click on one of the links the user navigates outside the page and no confirm dialog appears no nothing. Have I misunderstood the beforeunload event?


Solution

  • unfortunately, there is no way to override the default behaviour. Most browsers will just display the returnValue of the event, accompanied by an 'OK'/'Leave page' and 'Cancel' button. You can set that message though:

    window.onbeforeunload = function (e) {
            var e = e || window.event;
            // For IE and Firefox prior to version 4
            if (e) {
                e.returnValue = 'Hey, you are leaving. Do you want to continue?';
            }
            //you can do some last minute scripting here
            // For Safari
            return 'Hey, you are leaving. Do you want to continue?';
    };
    

    As suggested by Jason P, read more on it here