confirm() on [removed]

前端 未结 3 667
广开言路
广开言路 2020-12-01 22:11

I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:

window.onbeforeunload = function() {
    if          


        
相关标签:
3条回答
  • 2020-12-01 22:20
    window.onbeforeunload = function(e) {
        return 'Dialog text here.';
    };
    

    Docs:

    • https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
    • http://dev.w3.org/html5/spec-LC/history.html#unloading-documents

    Note that in Firefox 4 and later the returned string is not displayed to the user.

    If the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document. The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)

    0 讨论(0)
  • 2020-12-01 22:34

    Although window.onbeforeunload works, it's considered bad practice. It's better to use something like the following:

    if (typeof window.addEventListener === 'undefined') {
        window.addEventListener = function(e, callback) {
            return window.attachEvent('on' + e, callback);
        }
    }
    
    window.addEventListener('beforeunload', function() {
        return 'Dialog Text Here';
    });
    

    First we check if window.addEventListener exists, which it does not in IE, else we polyfill it, and then we attach the event.

    0 讨论(0)
  • 2020-12-01 22:38

    With jQuery, you can set the same handlers. The code may defer based on your version.

        function AnyFunction(e){ /**** your code *****/ };
    
        $(function () {
          $(window).bind('unload', function (e) { return AnyFunction(e); });
          $(window).bind('beforeunload', function (e) { return AnyFunction(e); });
        });
    

    You can also change the confirm or alert function using plugins as bootbox.

    0 讨论(0)
提交回复
热议问题