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


当前回答

没有事件,但是有一个属性窗口。在撰写本文时,所有主要浏览器都支持关闭。因此,如果您确实需要了解,可以轮询窗口以检查该属性。

如果(myWindow.closed){做事}

注意: 轮询任何东西通常都不是最佳解决方案。窗外。如果可能的话,应该使用Onbeforeunload事件,唯一的警告是,如果您导航离开,它也会触发。

其他回答

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) {

                                        }
               });
       }

来自MDN文档

由于某些原因,基于webkit的浏览器不符合对话框的规范。一个几乎交叉工作的例子与下面的例子很接近。

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

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

本例处理所有浏览器。

我的方法是:

使用onpopstate监听url中的变化,并将sessionStorage变量设置为1 监听页面加载并将sessionStorage变量设置为0 在beforeunload上,检查变量是否为0。如果是这样,这意味着用户正在关闭而不是改变url。

这仍然是一条迂回的路,但对我来说是有意义的

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

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

我需要在浏览器或选项卡关闭时自动注销用户,而不是当用户导航到其他链接时。我也不希望在发生这种情况时显示确认提示。在与这个问题斗争了一段时间后,尤其是在IE和Edge上,以下是我在基于这个答案的方法之后所做的(检查了在IE 11、Edge、Chrome和Firefox上的工作)。

首先,在JS中的beforeunload事件处理程序中启动服务器上的倒计时计时器。ajax调用需要同步,IE和Edge才能正常工作。你还需要使用return;防止确认对话框像这样显示:

    window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });

启动计时器将cancelLogout标志设置为false。如果用户刷新页面或导航到另一个内部链接,服务器上的cancelLogout标志将被设置为true。一旦计时器事件失效,它将检查cancelLogout标志,以查看注销事件是否已取消。如果计时器已经取消,那么它将停止计时器。如果浏览器或选项卡被关闭,那么cancelLogout标志将保持为false,事件处理程序将注销用户。

实现注意:我使用的是ASP。NET MVC 5和我取消注销在一个重写的Controller.OnActionExecuted()方法。