Javascript监听浏览器tab关闭

Javascipt监听浏览器tab关闭:

[color=violet]IE[/color]

支持得相对好一点:监听鼠标点击关闭按钮或者按Ctrl+F4组合键,在onunload处理函数中,浏览器可以发送请求到服务器,让服务器做相关的处理。


[color=violet]Safari, Firefox[/color]

能够在onunload处理函数中正确判断,但此时浏览器无法向服务器发送请求。
如果我们使用onbeforeunload处理函数,此时浏览器可以向服务器发送请求,但无法判断浏览器是刷新,转到别的页面还是关闭。


window.onunload = function unLoad( e ) {
if (window.event) { // IE browser, could work
e = window.event;
if (e.clientY < 0 || e.ctrlKey) { // Handle two scenarios: click the x button of the tab or press Ctrl + F4
logout();
}
} else if (window.event) { // Safari
if (document.documentElement.scrollWidth == 0) {
logout(); // Couldn't send the request to the server when unload event occurred in Safari
}
} else { // Firefox, could listen to the event, but couldn’t send the logout() request to server
if (document.documentElement.scrollWidth == 0) { // Alternatively, if we choose the window.onbeforeunload event, which could be triggered by refreshing the window or navigating to another page or closing the tab. This condition would never happen despite we could send the logout() request to server
logout();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值