Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: \"Are you sure you want
To expand on Keith's already amazing answer:
To allow custom warning messages, you can wrap it in a function like this:
function preventNavigation(message) {
var confirmOnPageExit = function (e) {
// If we haven't been passed the event get the window.event
e = e || window.event;
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
window.onbeforeunload = confirmOnPageExit;
}
Then just call that function with your custom message:
preventNavigation("Baby, please don't go!!!");
To re-enable navigation, all you need to do is set window.onbeforeunload
to null
. Here it is, wrapped in a neat little function that can be called anywhere:
function enableNavigation() {
window.onbeforeunload = null;
}
If using jQuery, this can easily be bound to all of the elements of a form like this:
$("#yourForm :input").change(function() {
preventNavigation("You have not saved the form. Any \
changes will be lost if you leave this page.");
});
Then to allow the form to be submitted:
$("#yourForm").on("submit", function(event) {
enableNavigation();
});
preventNavigation()
and enableNavigation()
can be bound to any other functions as needed, such as dynamically modifying a form, or clicking on a button that sends an AJAX request. I did this by adding a hidden input element to the form:
Then any time I want to prevent the user from navigating away, I trigger the change on that input to make sure that preventNavigation()
gets executed:
function somethingThatModifiesAFormDynamically() {
// Do something that modifies a form
// ...
$("#dummy_input").trigger("change");
// ...
}