简体   繁体   中英

How Do I Use JavaScript To Prevent A Window From Closing Without The Popup With The “Are You Sure You Want To Leave This Page” Message?

I have a page for editing some data, and have some buttons for saving the data and closing the page. The page also has a modal popup for prompting the user if they want to exit without saving any changes they've made (if they have made any).

However, whilst this works when the user clicks on the buttons, this does not work if they click on the X at the top right corner of the window. I can get the page to stop when they click on this, and ask the usual "Are You Sure You Want To Leave This Page" message, but this isn't as nice as the modal popup, and I'd rather the user saw the same message regardless of which way they tried to exit the screen.

Can anyone explain how to prevent the window from closing if the user has made changes, but without using the "Are You Sure You Want To Leave This Page" message, so that I can show my nice modal version instead please?

You can't. If you could, it would get abused. So you can't. Your only option is the onbeforeunload handler, which will (with modern browsers) show a default message (no longer a custom message). That's it.

var showMessage = false; // set it to true when you want the message shown on exit
window.onbeforeunload = function(e) {
    if (showMessage) {
        var event = e || window.event;
        var msg = "You have unsaved changes."; // Most modern browsers will no
                                               // longer actually show this
                                               // message, just their own.
                                               // But to trigger it, you have to
                                               // return one, so may as well make
                                               // it useful.
        if (event) {
            event.returnValue = msg; // IE
        }
        return msg;                  // Everyone else
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM