Javascript 页面卸载前的事件调用

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

Event calling before page unload

javascripthtml

提问by Suraj Air

I want to pop up a dialog before an htmlpage is unloaded asking to unload page or not. If yes is selected then the unload continues, and if no is selected then the unload event is canceled.

我想在html卸载页面之前弹出一个对话框,询问是否卸载页面。如果选择是,则卸载继续,如果选择否,则取消卸载事件。

回答by Nick Craver

You can't set the text to "yes"/"no" (it'll be "Ok"/"Cancel" in most browsers), but you can prompt (be careful when using this) when leaving the page in any manner using window.onbeforeunload, like this:

您不能将文本设置为“是”/“否”(在大多数浏览器中会是“确定”/“取消”),但是您可以在以任何方式离开页面时进行提示(使用时要小心)使用window.onbeforeunload,像这样:

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

Only use this if you have a good reason, don't annoy your users. That being said, this will prompt when leaving the page, that includes history back, forward, refresh, closing the window/tab, clicking a link to navigate away or submitting a form, etc. So you'll probably want to call this when going somewhere that shouldn't prompt:

仅在您有充分理由时才使用此功能,不要惹恼您的用户。话虽如此,这将在离开页面时提示,包括历史记录后退、前进、刷新、关闭窗口/选项卡、单击链接以导航离开或提交表单等。因此,您可能希望在以下情况下调用它去不应该提示的地方:

window.onbeforeunload = null;

For example, submitting a form of information, you'd want to prompt when leaving/losing the data, but not when actually submitting it.

例如,提交信息表单时,您希望在离开/丢失数据时提示,但在实际提交时不提示。