javascript window.onbeforeunload 不显示警告框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20067472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:37:10  来源:igfitidea点击:

window.onbeforeunload not displaying the alert box

javascriptonbeforeunload

提问by Alex

I just want to show a message before leaving the page, but my code doesn't works:

我只想在离开页面之前显示一条消息,但我的代码不起作用:

window.onload=function(){
    alert("Page with a digital clock");
    setInterval(clock,1000);
}

window.onbeforeunload=function(){
    alert("Are you sure to leave this page?");
}

The "onload alert" works fine, but the second is not working..

“加载警报”工作正常,但第二个不起作用..

回答by CodingIntrigue

You can't put an alert inside onbeforeunload. Most browsers will do this for you so you don't need to handle it, you need to return the confirm message to the method instead:

您不能在 onbeforeunload 内部放置警报。大多数浏览器都会为你做这件事,所以你不需要处理它,你需要将确认消息返回给方法:

window.onbeforeunload=function(){
    return "Are you sure to leave this page?";
}

Here are the docs for the method on MDN.

这是MDN 上该方法的文档。

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog

当此事件返回非空值时,系统会提示用户确认页面卸载。在大多数浏览器中,事件的返回值显示在这个对话框中