I have used onbeforeunload
event to show a default alert box when user tries to leave the page.
This dialog is showing in my Form Post action.
I have used event.preventDefault()
(for browsers except safari) and return null
for Safari to prevent showing this dialog in Form post action. But this is not working in firefox and IE.
Below is the jquery code sample
if (!isSafari) {
window.addEventListener("beforeunload", function (event) {
if (!hideDefaultAlert) {
event.returnValue = "Your unsaved changes will be lost";
} else {
event.preventDefault();
hideDefaultAlert = false;
}
});
} else if (isSafari) {
$(window).on("beforeunload", function () {
if (!hideDefaultAlert) {
return "Your unsaved changes will be lost";
} else {
hideDefaultAlert = false;
return null;
}
});
}
Please provide a solution for this to prevent this alert in Firefox and Safari.
Thanks in advance.
If the browser is not Safari and if the form is not changed, there is no need to display the dialog. So, please try to modify your code as below (remove the event.preventDefault()):
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor") > 0;
var hideDefaultAlert = true;
if (!isSafari) {
alert("not safari");
window.addEventListener("beforeunload", function (event) {
if (!hideDefaultAlert) {
event.returnValue = "Your unsaved changes will be lost";
} else {
//event.preventDefault(); //remove this line
hideDefaultAlert = false;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With