Search code examples
javascriptonbeforeunloadwindow.location

Navigate to other page when user clicks 'stay' on beforeunload


I need to have a way to do the following:

  1. When a user clicks to exit the window, it should ask if they want to stay or leave
  2. If a user clicks stay, it should direct them to a new page
  3. If a user clicks leave, the window should close

I currently have the following code:

var timeout;
$(window).on('beforeunload', function (){
    timeout = setTimeout(function() {
       alert('You stayed');
       window.location.href = 'desktop/salvage';
    }, 1000);
    return "You save some unsaved data, Do you want to leave?";
});

function noTimeout() {
    alert("You're leaving!");
    clearTimeout(timeout);
}

window.unload = noTimeout;

The alerts run correctly, but if a user clicks stay then the attempted navigation to another page runs beforeonload again and prompts you again. This gets stuck in an endless loop until you decide to leave the page, upon which you are navigated to the page you should be navigated to if you choose 'stay'.


Solution

  • Use a boolean flag to prevent the alert when you really want the user to be redirected to another page:

    var timeout;
    var redirecting = false;
    $(window).on('beforeunload', function (){
        if (redirecting) { return; }
        timeout = setTimeout(function() {
           alert('You stayed');
           redirecting = true;
           window.location.href = 'desktop/salvage';
        }, 1000);
        return "You save some unsaved data, Do you want to leave?";
    });
    
    function noTimeout() {
        alert("You're leaving!");
        clearTimeout(timeout);
    }
    
    window.unload = noTimeout;