在浏览器重新加载/关闭浏览器/退出页面之前执行Javascript函数

Execute Javascript function before browser reloads/closes browser/exits page?

本文关键字:浏览器 执行 函数 Javascript 退出 新加载 加载      更新时间:2023-09-26

在用户选择重新加载/关闭浏览器/退出页面之前,是否有方法执行函数?

我需要这个"在线/离线"状态功能,我正在尝试写。我想检测用户是否仍在页面上。

有什么想法吗?:)

也许有更好的方法?

内联函数:

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;
});

注:

当此事件返回非void值时,系统会提示用户确认页面卸载。在大多数浏览器中事件显示在此对话框中。

自2011年5月25日起,HTML5规范规定调用window.showModalDialog()、window.alert()、windows.confrm()和window.prompt()方法在此事件期间可能被忽略。

请参阅上的文档https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

使用window.obeforeunload,当用户离开页面时会触发:http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx

试试这个:

$( window ).unload(function() {
  alert( "Handler for .unload() called." );
});

或者如果你想要确认警报

<script>
window.onbeforeunload = function(e) {  
   return 'Your dialog message';
};
</script>