Confirm Dialog when i close the browser?

后端 未结 3 580
再見小時候
再見小時候 2020-12-06 06:41

i need to display confirm dialog box before close browser window using javascript or PHP. the confirm box should come when i click the close button of browser. other wise do

相关标签:
3条回答
  • 2020-12-06 06:57

    onunload is not very useful (in my opinion) as you can't do anything with the confirmation you're requesting (except maybe attempt to new another window with window.open, so onbeforeunload is more useful for this case.

    Your better bet is onbeforeunload, which is great but won't work in Opera (though this usually isn't a deal breaker).

    Like ivy said, it would look something like this:

    <script>
    
        var userIsEditingSomething; // set this if something crazy happens
            oldOnBeforeUnload = window.onbeforeunload;
    
        window.onbeforeunload = function () {
            // attempt to handle a previous onbeforeunload
            if ('function' === typeof oldOnBeforeUnload) {
                var message = oldOnBeforeUnload();
                if ('undefined' !== typeof message) {
                    if (confirm('string' === typeof message ? message : 'Are you sure you want to leave this page?')) {
                        return; // allow user to exit without further annoying pop-ups
                    }
                }
            }
            // handle our own
            if (userIsEditingSomething) {
                return 'Are you sure you want to exit?';
            }
        };
    
    </script>
    
    0 讨论(0)
  • 2020-12-06 07:00
    function doUnload()
    {
      // use confirm dialog box here
       confirm("Window is closing...");
    
    }
    
    <body onunload="doUnload()">
    
    0 讨论(0)
  • 2020-12-06 07:11

    You should handle the onbeforeunload event...

    function closeEditorWarning(){
        return 'Are you sure?'
    }
    window.onbeforeunload = closeEditorWarning;
    

    Or use jquery, window.attachEvent / window.addEventListener to do it nicely

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