开发者

Confirm Dialog when i close the browser?

i need to display confirm dialog box before close browser window using javascript or PHP. the confir开发者_StackOverflowm box should come when i click the close button of browser. other wise don't display dialog. please help me any.


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


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>


function doUnload()
{
  // use confirm dialog box here
   confirm("Window is closing...");

}

<body onunload="doUnload()">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜