How to Detect Browser Window /Tab Close Event?(如何检测浏览器窗口/选项卡关闭事件?)
问题描述
我正在尝试使用 onbeforeunload 和 Unload 功能.但它没有用.单击链接或刷新时,会触发此事件.我想要一个仅在浏览器窗口或选项卡关闭时触发的事件.该代码必须适用于所有浏览器.
I am Trying with onbeforeunload, and Unload function. But it didn't work. When clicking a link or refreshing, this event got triggered. I want an event that is triggered only when a browser window or tab is closed. The code must work in all browsers.
我在 Masterpage 中使用以下代码.
I am using Following code in Masterpage.
<script type="text/jscript">
var leaving = true;
var isClose = false;
function EndChatSession() {
var request = GetRequest();
request.open("GET", "../Chat.aspx", true);
request.send();
}
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if (keycode == 116) {
isClose = true;
}
}
function somefunction() {
isClose = true;
}
window.onbeforeunload = function (e) {
if (!e) e = event;
if (leaving) {
EndChatSession();
e.returnValue = "Are You Sure";
}
}
function GetRequest() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
在我的身体标签中:
以上代码在 IE 中有效,但在 chrome 中无效...
The Above code works in IE but not in chrome...
推荐答案
此代码可防止复选框事件.它在用户单击浏览器关闭按钮时起作用,但在单击复选框时不起作用.您可以为其他控件(texbox、radiobutton 等)修改它
This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)
window.onbeforeunload = function () {
return "Are you sure?";
}
$(function () {
$('input[type="checkbox"]').click(function () {
window.onbeforeunload = function () { };
});
});
这篇关于如何检测浏览器窗口/选项卡关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测浏览器窗口/选项卡关闭事件?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
