How to cancel the beforeunload event?

Is it even possible?

Using jQuery I am doing this:

$(window).bind('beforeunload', function() {
            if (confirm("are you sure you want to leave? changes will be lost")) {
                return true;
            }
            else {
                $("#content").css("background", "#df34ef");
                return false;
            }


            ;
        });

the problem is the ‘return false;’ statement results in the irritating default dialog being shown anyway - i want to cancel the event, prevent this dialog and return the user to my page…

AFAIK there is only one way to use the onBeforeUnload event.

The browser will take care of the dialog box, all you have to do is specify a string which will appear in the “Are you sure?” box:

 
window.onbeforeunload = function() {
    return "Are you sure you want to leave? changes will be lost";
} // This function MUST return a string (or something which is falsey)

If you want something to happen when the user presses cancel (i.e. they don’t want to leave the page), then you can set a setTimeout within that function:


window.onbeforeunload = function() {
    setTimeout(userDidNotLeave,10);
    return "Are you sure you want to leave? changes will be lost";
}

function userDidNotLeave() {
    $("#content").css("background", "#df34ef");
}

ok, thanks james… it’s such an obvious problem you would think there might be a better solution, but thanks for your suggestions anyway :slight_smile: