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 () { };
});
});
这篇关于如何检测浏览器窗口/选项卡关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测浏览器窗口/选项卡关闭事件?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01