六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 28|回复: 0

Javascript监听浏览器tab关闭

[复制链接]

升级  37.4%

217

主题

217

主题

217

主题

进士

Rank: 4

积分
687
 楼主| 发表于 2013-1-29 08:43:06 | 显示全部楼层 |阅读模式
Javascipt监听浏览器tab关闭:

IE

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


Safari, Firefox

能够在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();        }     }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表