JSFiddle - React, Tailwind, and code Playground
by jtaylor
HTML
<button id="somebutton">Click to make page dirty</button>
<br>
<a href="about:blank">Click to navigate away from this page</a>
JavaScript
var myObject = {
isDirty: false
};
// Note: I came across a couple articles saying we may should to use window.onbeforeunload instead of or in addition to jQuery's unload. Keep an eye on this.
// http://vidasp.net/jQuery-unload.html
// http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
var beforeUnloadEnabled = true; // We hook into window.onbeforeunload and bind some jQuery events to confirmBeforeUnload. This variable is used to prevent us from showing both messages during a single event.
var defaultUnloadText = "If you navigate away from the page now, you'll lose your changes to this page.";
var defaultUnloadTextConfirm = "Click OK to continue or Cancel to stay on this page";
// Prompt user before actions (excluding leaving the page) that could cause loss of data.
var confirmBeforeUnload = function(evt) {
if (!beforeUnloadEnabled) {
return;
}
if (myObject != null && myObject.isDirty) {
var ret = window.confirm(defaultUnloadText + " " + defaultUnloadTextConfirm);
beforeUnloadEnabled = false;
window.setTimeout(function() {
beforeUnloadEnabled = true;
}, ret ? 30000 : 1000);
if (evt && !ret) {
evt.stopPropagation();
}
return ret;
}
return true;
}
$(document).ready(function() {
// Prompt user before leaving the page.
window.onbeforeunload = function() {
if (!beforeUnloadEnabled) {
return;
}
if (myObject != null && myObject.isDirty) {
beforeUnloadEnabled = false;
window.setTimeout(function() {
beforeUnloadEnabled = true;
}, 2500);
return (defaultUnloadText);
}
}
$(window).unload(confirmBeforeUnload);
});
$(document).ready(function() {
$("#somebutton").click(function() {
myObject.isDirty = true;
$(this).text("Page is now...