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


当前回答

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

然而,我同意缺少真正的关闭事件是很糟糕的:例如,如果你想在真正关闭的情况下才在后端重置会话状态,这是一个问题。

其他回答

来自MDN文档

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

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

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

本例处理所有浏览器。

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.onbeforeunload = function () {
    return "Do you really want to close?";
};

我需要在浏览器或选项卡关闭时自动注销用户,而不是当用户导航到其他链接时。我也不希望在发生这种情况时显示确认提示。在与这个问题斗争了一段时间后,尤其是在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()方法。