Javascript 关闭浏览器时是否确认对话框?

Javascript 关闭浏览器时是否确认对话框?,javascript,Javascript,在使用javascript或PHP关闭浏览器窗口之前,我需要显示确认对话框。 当我点击浏览器的关闭按钮时,确认框应该出现。其他方面不显示对话框。 请随时帮助我。您应该处理onbeforeunload事件 function closeEditorWarning(){ return 'Are you sure?' } window.onbeforeunload = closeEditorWarning; 或者使用jquery,window.attachEvent/window.addEve

在使用javascript或PHP关闭浏览器窗口之前,我需要显示确认对话框。 当我点击浏览器的关闭按钮时,确认框应该出现。其他方面不显示对话框。
请随时帮助我。

您应该处理onbeforeunload事件

function closeEditorWarning(){
    return 'Are you sure?'
}
window.onbeforeunload = closeEditorWarning;
或者使用jquery,window.attachEvent/window.addEventListener来很好地完成这项工作

在我看来,OnLoad并不是很有用,因为您无法对请求的确认进行任何处理,除了可能尝试使用window.open新建另一个窗口外,所以在这种情况下,onbeforeunload更有用

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

}

<body onunload="doUnload()">
你最好的选择是onbeforeunload,这很好,但在Opera中不起作用,尽管这通常不会破坏交易

就像艾薇说的,它看起来像这样:

<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>

onbeforeunload是要使用的事件处理程序。无论用户出于何种原因离开页面,它都会触发。不仅在关闭浏览器时你是对的。尽管对于这个问题jquery等可能有一些很好的抽象,但几年前我曾测试过条件event.clientX<0 | | event.clientY<0来区分按下窗口关闭按钮的人与正常导航操作之间的区别:条件为真,然后是链接、提交表单、后退、前进。这不是一个防故障的解决方案,例如ALT-F4未被捕获,因此我希望有人能为您提供更好的解决方案。如果您想取消确认对话框,例如在验证用户尚未开始编写或编辑某些内容后,您可以从回调返回undefined。然而,如果您返回null或false,IE会显示一条消息,粗略地询问您是否想要null或false,这很奇怪。