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来很好地完成它

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

}

<body onunload="doUnload()">
{ //在此处使用“确认”对话框 确认(“窗口正在关闭…”); }
onunload
不是很有用(在我看来),因为您无法对所请求的
确认
操作执行任何操作(除了可能尝试使用
窗口新建另一个窗口。打开
,因此
onbeforeuload
在这种情况下更有用

您最好的选择是
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>

var userIsEditingSomething;//如果发生异常情况,请设置此选项
oldOnBeforeUnload=window.onbeforeunload;
window.onbeforeunload=函数(){
//尝试在卸载之前处理上一个OnForeUnload
if('function'==typeof oldOnBeforeUnload){
var message=oldOnBeforeUnload();
如果('undefined'!==消息类型){
如果(确认('string'==typeof message?message:'确定要离开此页吗?')){
return;//允许用户退出,无需进一步弹出恼人的弹出窗口
}
}
}
//自己处理
if(userIsEditingSomething){
return“您确定要退出吗?”;
}
};

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