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


当前回答

//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});

JSFiddle Link

嗨,大家好,我能够通过使用浏览器本地存储和时间戳实现“检测浏览器和选项卡关闭事件”点击。希望你们所有的问题都能通过这个解决方案得到解决。

在我最初的研究之后,我发现当我们关闭浏览器时,浏览器会一个接一个地关闭所有的选项卡来完全关闭浏览器。因此,我观察到关闭制表符之间的时间延迟非常小。所以我把这个时间延迟作为我的主要验证点,并能够实现浏览器和选项卡关闭事件检测。

我在Chrome浏览器版本76.0.3809.132上测试了它,发现可以工作

:)如果你觉得我的回答有帮助,请投票....

其他回答

如果我没说错,你想知道什么时候一个标签/窗口是有效关闭的。好吧,在JavaScript中检测这个的唯一方法是使用onunload或onbeforeunload事件。

不幸的是(或幸运的是?),当您通过链接或浏览器的后退按钮离开网站时,这些事件也会被触发。这是我能给出的最好答案,我不认为你能在JavaScript中原生检测纯close。如果我说错了,请指正。

简单的解决方案

window.onbeforeunload = function () {
    return "Do you really want to close?";
};

我找到了一个方法,在我所有的浏览器上都能运行。

测试在以下版本: Firefox 57, Internet Explorer 11, Edge 41,最新的Chrome浏览器之一(无法显示我的版本)

注意:onbeforeunload火灾如果你离开页面以任何可能的方式(刷新,关闭浏览器,重定向,链接,提交..)。如果只希望它在浏览器关闭时发生,只需绑定事件处理程序。

  $(document).ready(function(){         

        var validNavigation = false;

        // Attach the event keypress to exclude the F5 refresh (includes normal refresh)
        $(document).bind('keypress', function(e) {
            if (e.keyCode == 116){
                validNavigation = true;
            }
        });

        // Attach the event click for all links in the page
        $("a").bind("click", function() {
            validNavigation = true;
        });

        // Attach the event submit for all forms in the page
        $("form").bind("submit", function() {
          validNavigation = true;
        });

        // Attach the event click for all inputs in the page
        $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        }); 

        window.onbeforeunload = function() {                
            if (!validNavigation) {     
                // ------->  code comes here
            }
        };

  });

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.

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

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

                                        }
               });
       }