javascript - 如何检测 2021 年使用 javascript 关闭的标签页?
问题描述
对此最受欢迎的问题有很多答案,但遗憾的是我找不到一个可以正常工作的问题。大多数回复来自 10 年前,有些甚至不起作用:
同一段代码也有许多变体(例如,有些在代码中添加了“e.returnValue='';”,而其他许多则没有。
进行此检测的最佳方法是什么?还是在卸载之前吗?2021 年代码将如何涵盖现代浏览器/行为?
(为了避免 XY 问题,如果用户试图关闭页面,我想显示一个确认弹出窗口。弹出窗口很容易,检测不是。)
解决方案
这是重复的。另一个问题的答案指定onunload
和beforeunload
事件,两者都具有很好的浏览器兼容性(onunload和beforeunload)。
我在浏览器控制台中尝试了这个解决方案(随机选择),它开箱即用:
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.
推荐阅读
- jquery - 登录成功后显示一次 toastr
- python - 如何结束启动 SSMS 的 python 脚本的运行?
- haskell - 字符串到术语,如果不存在术语 - 捕获错误
- php - 如何将帖子 ID 从 foreach 循环传输到具有用于报告 laravel 8 中的帖子的表单的报告页面
- amazon-web-services - 将文件上传到 Cloudfront 后面的 EC2
- javascript - JavaScript: what is the fastest hexadecimal string to ArrayBuffer algorithm?
- reactjs - 如何将图像导入到对象的 initialState 数组中,然后通过它进行映射以显示?
- html - there is some space left after applying background-size : cover; property
- c - Convert String Text File in C to Hexadecimal encoding
- python - Trying to make assistant but facing speed problem