javascript 在任何情况下都阻止 onbeforeunload 关闭页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30781070/
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
prevent onbeforeunload to close page in any case
提问by Goodbye StackExchange
I want to prevent browser to close page in any case or in other case, Prevent browser to do anything when onbeforeunload
is called.
Here is my code which i have tried.
我想阻止浏览器在任何情况下或其他情况下关闭页面,在onbeforeunload
调用时阻止浏览器执行任何操作。这是我尝试过的代码。
(function() {
var proxied = window.onbeforeunload;
window.onbeforeunload = function(e) {
e.preventDefault();
e.stopPropagation();
//i want to stop everything
console.log('stay here');
// return 'message';
};
})();
- I want to perform a action before leaving the page (disconnect the chat)
- 我想在离开页面之前执行一个操作(断开聊天)
回答by Goodbye StackExchange
You can't outright prevent a user from leaving the page (This would lead to much abuse on spam/advertisement sites who try to get you to stay on a page), but you can show things such as a window which causes a confirm prompt to the user. Have a look at Prevent a webpage from navigating away using JavaScriptwhich can lead you to the right direction of what you're trying to accomplish.
您不能完全阻止用户离开页面(这会导致垃圾邮件/广告网站大量滥用试图让您停留在页面上的内容),但您可以显示诸如导致确认提示的窗口之类的内容给用户。查看使用 JavaScript 防止网页导航离开,这可以引导您朝着正确的方向努力完成任务。
回答by Ijaz Ahmed Bhatti
There is no way to stop browser to close. The browser doesn't allow you to do that.
没有办法阻止浏览器关闭。浏览器不允许您这样做。