Search code examples
jqueryinternet-explorerfirefoxonbeforeunload

Prevent onbeforeunload alert using jquery in Firefox and IE


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.


Solution

  • 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;
                }           
            });
        }