是否有任何跨浏览器的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.

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

其他回答

$(window).unload( function () { alert("Bye now!"); } );

试试这个。它会起作用的。Jquery卸载方法。

window.onbeforeunload = function(event) {
    event.returnValue = "Write something clever here..";
};

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

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

                                        }
               });
       }

在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!';
  }
}