Search code examples
javascriptjqueryonbeforeunload

window.onbeforeunload may fire multiple times


Just because you don't see use for a feature doesn't mean it isn't useful.

The Stack Exchange network, GMail, Grooveshark, Yahoo! Mail, and Hotmail use the onbeforeunload prompt to prevent/warn users that they are leaving a page after they have begun editing something. Oh yah, nearly every single desktop program that accepts saveable user-input data utilizes this prompt-user-before-leaving UX pattern.


I have a function which behaves similarly to this one:

window.onbeforeunload = function(){
    // only prompt if the flag has been set... 
    if(promptBeforeLeaving === true){
        return "Are you sure you want to leave this page?";
    }
}

When a user attempts navigates away from the page the browser presents them with the option to leave or stay on the page. If the user selects the "Leave this page option" and then they quickly click on a link again before the page unloads completely the dialog fires again.

Are there any foolproof solutions to this problem?


Note: The following NOT the solution:

var alreadyPrompted = false;
window.onbeforeunload = function(){
    // only prompt if the flag has been set... 
    if(promptBeforeLeaving === true && alreadyPrompted === false){
        alreadyPrompted = true;
        return "Are you sure you want to leave this page?";
    }
}

because the user might select the "Stay on the page" option which would cause future onbeforeunloads to stop working.


Solution

  • I think you could accomplish this with a timer (setInterval) that starts in the onbeforeunload callback. Javascript execution will be paused while the confirm dialog is up, then if the user cancels out the timed function could reset the alreadyPrompted variable back to false, and clear the interval.

    Just an idea.

    Ok I did a quick test based on your comment.

    <span id="counter">0</span>
    window.onbeforeunload = function () {
       setInterval(function () { $('#counter').html(++counter); }, 1);
       return "are you sure?";
    }
    window.onunload = function () { alert($('#counter').html()) };
    

    In between the two callbacks #counter never got higher than 2 (ms). It seems like using these two callbacks in conjunction gives you what you need.

    EDIT - answer to comment:

    Close. This is what i was thinking

    var promptBeforeLeaving = true,
        alreadPrompted = false,
        timeoutID = 0,
        reset = function () {
            alreadPrompted = false;
            timeoutID = 0;
        };
    
    window.onbeforeunload = function () {
        if (promptBeforeLeaving && !alreadPrompted) {
            alreadPrompted = true;
            timeoutID = setTimeout(reset, 100);
            return "Changes have been made to this page.";
        }
    };
    
    window.onunload = function () {
        clearTimeout(timeoutID);
    };