Monday, September 21, 2009

How to stop and prompt user when closing browser

Scenario:

For some reason you want to stop the user from closing the browser window or from redirecting away from the current page, based on some condition.


The solution:

window.onbeforeunload = function(event) {
return true;
}

This will prompt you for input (like the JavaScript confirm pop-up menu). There is no way to override the text though.

Some concerns:
This works great but it may not be what you want all the time, as no matter if you click a hyperlink, hit submit, etc will prompt the user. So here is an example where only when any input value on the screen has changed, I want to prompt the user only then and also only if the user decides to redirect from the page. It should not prompt the user when I try and save/delete or update the page:

var dataUpdated = false;

$(document).ready(function() {
SetupChangeEventOnAllInputElementsAndSetGlobalFlag();
})

function SetupChangeEventOnAllInputElementsAndSetGlobalFlag() {
$(':input').change(function() {
dataUpdated = true;

window.onbeforeunload = function(evt) {

var e = e || window.event;

// For IE and Firefox
if (e) {
if (DetermineSubmit(evt) == true)
return;
else
e.returnValue = 'You have not saved your changes - OK to ignore or Cancel to remain on this page?';
}
else {
// For Safari
if (DetermineSubmit(evt) == true)
return
else
return 'You have not saved your changes - OK to ignore or Cancel to remain on this page?';
}
}

});

}

//Determine if the original event is a submit button/control that triggered the window unload
function DetermineSubmit(evt) {
if ($(evt.explicitOriginalTarget).is(':submit')) {
return true;
}

return false;
}

No comments:

Post a Comment