有没有一种方法在用户选择重新加载/关闭浏览器/退出页面之前执行函数?
我需要这个功能来编写一个“在线/离线”状态函数。我想检测用户是否仍然在页面上。
有什么想法吗? :)
也许有更好的方法?
有没有一种方法在用户选择重新加载/关闭浏览器/退出页面之前执行函数?
我需要这个功能来编写一个“在线/离线”状态函数。我想检测用户是否仍然在页面上。
有什么想法吗? :)
也许有更好的方法?
内联函数:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
或通过事件监听器(推荐):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
或者如果你已经使用了jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
注意:
当此事件返回非空值时,用户将被提示确认页面卸载。在大多数浏览器中,该事件的返回值将在此对话框中显示。
自2011年5月25日起,HTML5规范指出,在此事件期间,对window.showModalDialog()、window.alert()、window.confirm()和window.prompt()方法的调用可能会被忽略。
请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload文档。
试试这个:
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});
或者如果您想要确认警报,则使用此代码
<script>
window.onbeforeunload = function(e) {
return 'Your dialog message';
};
</script>
使用window.onbeforeunload,当用户离开您的页面时会触发它: http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx