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


当前回答

简单的解决方案

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

其他回答

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

                                        }
               });
       }

我的方法是:

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

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

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

如果(myWindow.closed){做事}

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

window.onbeforeunload = function() {
  console.log('event');
  return false; //here also can be string, that will be shown to the user
}

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

测试在以下版本: 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
            }
        };

  });