Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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;
The solution for this is, need to replace event.preventDefault() with event.stopPropagation() and return undefined. This solution works in all the browser.
if (!isSafari) {
window.addEventListener("beforeunload", function (event) {
if (!hideDefaultAlert) {
event.returnValue = "Your unsaved changes will be lost";
} else {
event.stopPropagation();
hideDefaultAlert = false;
return undefined;
} else if (isSafari) {
$(window).on("beforeunload", function () {
if (!hideDefaultAlert) {
return "Your unsaved changes will be lost";
} else {
hideDefaultAlert = false;
return null;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.