首页 > 解决方案 > 如何检测 2021 年使用 javascript 关闭的标签页?

问题描述

对此最受欢迎的问题有很多答案,但遗憾的是我找不到一个可以正常工作的问题。大多数回复来自 10 年前,有些甚至不起作用:

检测浏览器或标签页关闭

同一段代码也有许多变体(例如,有些在代码中添加了“e.returnValue='';”,而其他许多则没有。

进行此检测的最佳方法是什么?还是在卸载之前吗?2021 年代码将如何涵盖现代浏览器/行为?

(为了避免 XY 问题,如果用户试图关闭页面,我想显示一个确认弹出窗口。弹出窗口很容易,检测不是。)

标签: javascriptjqueryconfirm

解决方案


这是重复的。另一个问题的答案指定onunloadbeforeunload事件,两者都具有很好的浏览器兼容性(onunloadbeforeunload)。

我在浏览器控制台中尝试了这个解决方案(随机选择),它开箱即用:

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 

此外,该问题的 3~4 个答案是在 2018 年之后!他们怎么能老?!

我最终将编辑答案以包含有关该特定页面如何执行此操作的详细信息。

编辑:我检查了页面,唯一的检查是:

$(window).unbind().bind('beforeunload', function(){
  return 'You are about to disconnect from this chat, are you sure you want to leave?';
});

这段代码是逐字记录的,而且很糟糕。正如@charlietfl所提到的,bind()并且unbind()是不推荐使用的方法。从文档中:

As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

So please use on() instead.


推荐阅读