How to show the “Are you sure you want to navigate away from this page?” when changes committed?

前端 未结 17 1787
深忆病人
深忆病人 2020-11-22 02:11

Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: \"Are you sure you want

17条回答
  •  Happy的楠姐
    2020-11-22 02:55

    The onbeforeunload Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).

    Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.

    Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):

    function enableBeforeUnload() {
        window.onbeforeunload = function (e) {
            return "Discard changes?";
        };
    }
    function disableBeforeUnload() {
        window.onbeforeunload = null;
    }
    

    Then define a form like this:

    This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.

提交回复
热议问题