Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Dinesh M Avatar asked Nov 07 '22 16:11

Dinesh M


1 Answers

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;
                }
            });
        }
like image 57
Zhi Lv Avatar answered Nov 12 '22 18:11

Zhi Lv