Skip to content

Instantly share code, notes, and snippets.

@arturmamedov
Last active July 9, 2019 16:35
Show Gist options
  • Save arturmamedov/385869322c5394696004a95abb8f6be1 to your computer and use it in GitHub Desktop.
Save arturmamedov/385869322c5394696004a95abb8f6be1 to your computer and use it in GitHub Desktop.
Window on before unload - for stop user to escape page before all data is not saved or an action not performed
// Message to be displayed on unload
var message = $('#jtrnslt #leavemess').text(), submitting = false;
// On Form submition set submitting to true for not fire onbeforeunload
$(document).on("submit", "form", function(event){
submitting = true;
});
// Window onbeforeunload fired when leave page but not if it a form submition or element with .noBeforeUnload class
window.onbeforeunload = function (e) {
e = e || window.event;
// Determine if you want to allow unload
/* some synchronous operation here*/
if (!submitting && !$(e.target.activeElement).hasClass('noBeforeUnload')) {
// IE BUG: throws unspecified error on "cancel"
// so we temporarily mask all Javascript errors
window.onerror = function (msg, url, linenumber) {
return -1 < msg.toLowerCase().indexOf('unspecified error');
};
// After return the (blocking) confirmation window is shown
// after which we remove Javascript error handler
window.setTimeout(function () {
window.onerror = function () {
return false;
}
}, 100);
// -- IE BUG
// IE expects the confirmation string in the
// `returnValue` property of event object
if (e) {
e.returnValue = message;
}
// Other browsers expect it returned as a string
return message;
}
};
@arturmamedov
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment