javascript 在 Java Script 中关闭窗口之前显示警告消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15514674/
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 01:02:46  来源:igfitidea点击:

Show warning message before close window in Java Script

javascript

提问by Coolguy

I've try this:

我试过这个:

<body onunload="LogoutNoAsk();"> </body>

and the function is:

功能是:

function LogoutNoAsk()
{
    alert("Please press the Logout button to logout.");
    parent.close();

}

When I press close which is the 'X' button on the top right of the window, it close straightaway without the warning message. What's wrong?

当我按下窗口右上角的“X”按钮关闭时,它会立即关闭而没有警告消息。怎么了?

回答by Aaron Powell

You're actually wanting to use the onbeforeunloadevent which allows you to block the close event.

您实际上想要使用onbeforeunload允许您阻止关闭事件的事件。

See the MDN referencefor details, but the code required would be:

有关详细信息,请参阅MDN 参考,但所需的代码是:

window.onbeforeunload = function(e) {
    return 'Please press the Logout button to logout.';
};