在浏览器重新加载/关闭浏览器/退出页面之前执行 Javascript 功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14746851/
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
Execute Javascript function before browser reloads/closes browser/exits page?
提问by Alosyius
Is there a way to execute a function before a user chooses to reload/close browser/exit page?
有没有办法在用户选择重新加载/关闭浏览器/退出页面之前执行功能?
I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.
我需要这个用于我正在尝试编写的“在线/离线”状态功能。我想检测用户是否仍在页面上。
Any ideas? :)
有任何想法吗?:)
Maybe there is a better approach to this?
也许有更好的方法来解决这个问题?
回答by Samuel Liew
Inline function:
内联函数:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
or via an event listener (recommended):
或通过事件侦听器(推荐):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
or if you have jQuery:
或者如果你有 jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Notes:
笔记:
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.
Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.
当此事件返回非空值时,系统会提示用户确认页面卸载。在大多数浏览器中,事件的返回值显示在此对话框中。
自 2011 年 5 月 25 日起,HTML5 规范规定在此事件期间可以忽略对 window.showModalDialog()、window.alert()、window.confirm() 和 window.prompt() 方法的调用。
See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload 上的文档
回答by Mandar Limaye
Use window.onbeforeunload, it is triggered when user leaves your page :http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx
使用 window.onbeforeunload,当用户离开您的页面时触发:http: //geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closure-或禁用.aspx
回答by asok Buzz
Try this:
试试这个:
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});
OR this if you want conformation alert
或者如果你想要构象警报
<script>
window.onbeforeunload = function(e) {
return 'Your dialog message';
};
</script>