I have this little piece of code:
Super old question but might be useful to others.
Simply detaching the "beforeunload" from the "submit" event would not work for me - because the submit handler was being called even when there were errors in the form that the user had to fix. So if a user attempted to submit the form, then received the errors, then clicked to another page, they would be able to leave without the warning.
Here's my workaround that seems to work pretty well.
(function($) {
var attached = false,
allowed = false;
// catch any input field change events bubbling up from the form
$("form").on("change", function () {
// attach the listener once
if (!attached) {
$("body").on("click", function (e) {
// check that the click came from inside the form
// if it did - set flag to allow leaving the page
// otherwise - hit them with the warning
allowed = $(e.target).parents("form").length != 0;
});
window.addEventListener('beforeunload', function (event) {
// only allow if submit was called
if (!allowed) {
event.preventDefault();
event.returnValue = 'You have unsaved changes.';
}
});
}
attached = true;
});
}(jQuery));
This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning. If the click to leave the page originated from outside of the form, then it will warn the user.