Confirm Dialog when i close the browser?

2020-02-01 01:26发布

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 don't display dialog. please help me any.

标签: javascript
3条回答
ゆ 、 Hurt°
2楼-- · 2020-02-01 02:16

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>
查看更多
够拽才男人
3楼-- · 2020-02-01 02:21

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

查看更多
放我归山
4楼-- · 2020-02-01 02:23
function doUnload()
{
  // use confirm dialog box here
   confirm("Window is closing...");

}

<body onunload="doUnload()">
查看更多
登录 后发表回答