Javascript监听浏览器tab关闭

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();
        } 
    }
}

你可能感兴趣的:(JavaScript,tab,browser,close)