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

10
我需要使用JavaScript或PHP在关闭浏览器窗口之前显示确认对话框。 确认框应该在我单击浏览器的关闭按钮时出现。否则不显示对话框。 请帮帮我。
3个回答

23

你应该处理 onbeforeunload 事件...

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

或者使用jQuery,window.attachEvent / window.addEventListener 来实现更好的效果


3
如果你想要抑制确认对话框,例如在验证用户尚未开始编写或编辑内容之后,可以从回调函数中返回 undefined。但是,如果你返回 nullfalse,IE 将显示一条消息,询问你是否想要使用 nullfalse,这似乎有些奇怪。 - KajMagnus

1

onunload 在我看来并不是很有用,因为你无法对你请求的 confirm 做任何事情(除了可能尝试使用 window.open 打开一个新窗口),所以在这种情况下,onbeforeunload 更加有用。

你最好使用 onbeforeunload,它非常好用,但在 Opera 中不起作用(虽然这通常不是致命问题)。

就像 Ivy 说的那样,它会看起来像这样:

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

而且,无论出于何种原因,只要用户离开页面,它就会触发。不仅在关闭浏览器时触发。 - mplungjan
你是对的。虽然针对这个问题可能有很好的抽象化方法(如 jquery 等),但是多年前我曾使用测试条件“(event.clientX < 0 || event.clientY < 0)”来区分某人按下窗口关闭按钮(条件为真)和正常的导航操作(跟随链接、提交表单、后退、前进)。这不是一个万无一失的解决方案(例如,ALT-F4 没有被捕获),因此我希望有人能提供更好的解决方案。 - ivy

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

}

<body onunload="doUnload()">

1
onbeforeunload是要使用的事件处理程序。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接