Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

I am popping up a dialog box when someone tries to navigate away from a particular page without having saved their work. I use Javascript’s onbeforeunload event, works great.

Now I want to run some Javascript code when the user clicks “Cancel” on the dialog that comes up (saying they don’t want to navigate away from the page).

Is this possible? I’m using jQuery as well, so is there maybe an event like beforeunloadcancel I can bind to?

UPDATE: The idea is to actually save and direct users to a different webpage if they chose cancel

Answer

You can do it like this:

$(function() {
    $(window).bind('beforeunload', function() {
        setTimeout(function() {
            setTimeout(function() {
                $(document.body).css('background-color', 'red');
            }, 1000);
        },1);
        return 'are you sure';
    });
}); 

The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

example: http://www.jsfiddle.net/NdyGJ/2/

Leave a Reply

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