I need to have a way to do the following:
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'.
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;