是否有任何跨浏览器的JavaScript/jQuery代码来检测浏览器或浏览器标签是否正在关闭,但不是由于链接被单击?


当前回答

由于没有人提到它(8年多以后):WebSocket可以是检测关闭选项卡的另一种有效方法。只要选项卡打开并指向主机,客户端就能够保持到主机的活动WebSocket连接。

警告:请注意,这个解决方案只适用于WebSocket不需要任何额外的重大开销的项目。

在合理的超时时间内(例如2分钟),服务器端可以在WebSocket断开连接后确定客户端已经离开,并执行所需的任何操作,例如删除上传的临时文件。(在我非常专业的用例中,我的目标是在WebSocket连接断开和所有CGI/FastCGI活动终止三秒钟后终止本地主机应用服务器-任何其他保持活动的连接都不会影响我。)

我有问题让onunload事件处理程序正确地与信标一起工作(正如这个答案所推荐的)。关闭选项卡似乎不会触发信标,而打开选项卡则会以可能导致问题的方式触发信标。WebSocket更干净地解决了我遇到的问题,因为连接关闭的时间与选项卡关闭的时间大致相同,在应用程序中切换页面只是在延迟窗口内打开一个新的WebSocket连接。

其他回答

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 
window.onbeforeunload = function ()
{       

    if (isProcess > 0) 
    {
        return true;       
    }   

    else
    { 
        //do something      
    }
}; 

此功能在浏览器运行过程中关闭窗口或刷新页面时显示确认对话框。该函数适用于所有浏览器。你必须在ajax进程中设置isProcess var。

在window的帮助下可以检查。在'unload'事件的事件处理程序中关闭,但超时使用是必需的(所以结果不能保证如果SMTH延迟或阻止窗口关闭):

JSFiddle的例子(测试在最新的Safari, FF, Chrome, Edge和IE11)

var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
   <head><title>CHILD WINDOW/TAB</title></head>
   <body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
    document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
    document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
    setTimeout(()=>{
        document.querySelector('.status').innerHTML +=  getChildWindowStatus();
    },1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
    alert(getChildWindowStatus());
}
function getChildWindowStatus() {
  if (win.closed) { 
      return 'Child window has been closed!';
  } else {
      return 'Child window has not been closed!';
  }
}

I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me. I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:

<body onUnload="LogOff()">

然后添加LogOff函数重定向到Account/LogOff,这是Asp中的内置方法。净MVC。现在,当我关闭浏览器或选项卡,它重定向到LogOff方法和用户必须登录时返回。我已经在Chrome和Firefox中进行了测试。它确实有效!

  function LogOff() {
        $.ajax({
            url: "/Account/LogOff",
            success: function (result) {

                                        }
               });
       }

对于类似的任务,可以使用sessionStorage在本地存储数据,直到关闭浏览器选项卡。

sessionStorage对象仅存储一个会话的数据(当浏览器选项卡关闭时,该数据将被删除)。

这是我的钢笔。

<div id="Notice">
    <span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
    $("#Notice").click(function() {
     //set sessionStorage on click
        sessionStorage.setItem("dismissNotice", "Hello");
        $("#Notice").remove();
    });
    if (sessionStorage.getItem("dismissNotice"))
    //When sessionStorage is set Do stuff...
        $("#Notice").remove();
</script>