Is there a callback for cancelling window.onbeforeunload

There is no callback for staying on the page, but there is one for leaving the page, window.unload.

Try setting a timeout in beforeunload, then clear it in unload. If you stay, the timeout will run, otherwise it’ll be cleared.

var timeout;

function warning() {
    timeout = setTimeout(function() {
        alert('You stayed');
    }, 1000);
    return "You are leaving the page";
}

function noTimeout() {
    clearTimeout(timeout);
}

window.onbeforeunload = warning;
window.unload = noTimeout;​

DEMO: http://jsfiddle.net/aPwfz/1/

Leave a Comment