【问题标题】:How to Detect Browser Window /Tab Close Event?如何检测浏览器窗口/选项卡关闭事件?
【发布时间】:2014-02-09 05:34:21
【问题描述】:

我正在尝试使用 onbeforeunload 和 Unload 功能。但它没有用。单击链接或刷新时,会触发此事件。我想要一个仅在浏览器窗口或选项卡关闭时触发的事件。该代码必须适用于所有浏览器。

我在 Masterpage 中使用以下代码。

<script type="text/jscript">

    var leaving = true;
    var isClose = false;

    function EndChatSession() {
        var request = GetRequest();
        request.open("GET", "../Chat.aspx", true);
        request.send();
    }
    document.onkeydown = checkKeycode
    function checkKeycode(e) {
        var keycode;
        if (window.event)
            keycode = window.event.keyCode;
        else if (e)
            keycode = e.which;
        if (keycode == 116) {
            isClose = true;
        }
    }
    function somefunction() {
        isClose = true;
    }
    window.onbeforeunload = function (e) {
       if (!e) e = event;
        if (leaving) {
             EndChatSession();
             e.returnValue = "Are You Sure";

        }
    }
    function GetRequest() {
        var xmlHttp = null;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            //Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }    
</script>

在我的身体标签中:

以上代码在 IE 中有效,但在 chrome 中无效...

【问题讨论】:

    标签: javascript asp.net session


    【解决方案1】:

    此代码可防止复选框事件。它在用户单击浏览器关闭按钮时起作用,但在单击复选框时不起作用。您可以为其他控件(texbox、radiobutton 等)修改它

        window.onbeforeunload = function () {
            return "Are you sure?";
        }
    
        $(function () {
            $('input[type="checkbox"]').click(function () {
                window.onbeforeunload = function () { };
            });
        });
    

    【讨论】:

    • 刷新时也会调用警报。 . . .排除刷新事件的任何想法
    【解决方案2】:

    您无法使用 javascript 检测它。

    仅检测页面卸载/关闭的事件是window.onbeforeunloadwindow.unload。这些事件都不能告诉您关闭页面的方式。

    【讨论】:

      【解决方案3】:
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
      <script type="text/javascript">
      var validNavigation = false;
      
      function wireUpEvents() {
      var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
       var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
       function goodbye(e) {
      if (!validNavigation) {
      window.open("http://serverthemes.net/best-web-hosting-services","_blank");
      return leave_message;
      
      }
      }
      window.onbeforeunload=goodbye;
      
      // Attach the event keypress to exclude the F5 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;
       });
      
       }
      
        // Wire up the events as soon as the DOM tree is ready
         $(document).ready(function() {
         wireUpEvents();
         });
         </script>
      

      我确实在Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?回答了

      【讨论】:

        【解决方案4】:

        你也可以像下面这样。

        将下面的脚本代码放在标题标签中

        <script type="text/javascript" language="text/javascript"> 
        function handleBrowserCloseButton(event) { 
           if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) 
            {
              //Call method by Ajax call
              alert('Browser close button clicked');    
            } 
        } 
        </script>
        

        从下面的body标签调用上面的函数

        <body onbeforeunload="handleBrowserCloseButton(event);">
        

        谢谢

        【讨论】:

          【解决方案5】:

          为了区分刷新和关闭的选项卡或导航器,这是我修复它的方法:

          <script>
              function endSession() {
                   // Browser or Broswer tab is closed
                   // Write code here
              }
          </script>
          
          <body onpagehide="endSession();">
          
          </body>

          【讨论】:

          • 您的代码不能完美地检测关闭选项卡/窗口,因为在离开页面时会触发 onpagehide。例如。通过点击链接、刷新页面、提交表单、关闭浏览器窗口等。
          【解决方案6】:

          Solution Posted Here

          经过初步研究发现,当我们关闭浏览器时,浏览器会一一关闭所有标签页,从而彻底关闭浏览器。因此,我观察到关闭标签之间的时间延迟非常小。所以我把这个时间延迟作为我的主要验证点,并能够实现浏览器和标签关闭事件的检测。

          //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

          【讨论】:

            【解决方案7】:

            我的解决方案与Server Themes给出的解决方案类似。请检查一次:

            localStorage.setItem("validNavigation", false);
            $(document).on('keypress', function (e) {
                if (e.keyCode == 116) {
                    localStorage.setItem("validNavigation", true);
                }
            });
            
            // Attach the event click for all links in the page
            $(document).on("click", "a", function () {
                localStorage.setItem("validNavigation", true);
            });
            
            // Attach the event submit for all forms in the page
            $(document).on("submit", "form", function () {
                localStorage.setItem("validNavigation", true);
            });
            
            // Attach the event click for all inputs in the page
            $(document).bind("click", "input[type=submit]", function () {
                localStorage.setItem("validNavigation", true);
            });
            
            $(document).bind("click", "button[type=submit]", function () {
                localStorage.setItem("validNavigation", true);
            });
            window.onbeforeunload = function (event) {
            
                if (localStorage.getItem("validNavigation") === "false") {
                    event.returnValue = "Write something clever here..";
                    console.log("Test success!");
                    localStorage.setItem("validNavigation", false);
                }
            };
            

            如果你在浏览器页面上正确设置了断点,那么只有在浏览器即将关闭或标签页即将关闭时,if条件才会为真。

            查看此链接以供参考:https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

            【讨论】:

              【解决方案8】:

              是的,有!经过一番头疼后,我找到了一个解决方案。

              Monitor.php

              这个 php 文件将监控浏览器关闭事件。一旦浏览器关闭,connection_aborted 将返回 1,因此循环将中断。

              <?php
              // Ignore user aborts and allow the script
              // to run forever
              ignore_user_abort(true);
              set_time_limit(0);
              
              echo connection_aborted();
              while(1)
              {
              echo "Whatever you echo here wont be printed anywhere but it is required in order to work.";
              flush();
              if(connection_aborted())
              {
              break;
              // Breaks only when browser is closed
              }
              }
              
              /*
              Action you want to take after browser is closed.
              Write your code here
              */
              ?>
              

              来电者.php

              这是调用 Monitor.php 的文件

              <?php
              Header('Location: monitor.php');
              ?>
              

              父.html

              这将是您实际与之交互的文件。在加载时,它将直接对 Caller.php 进行 AJAX 调用,这将在后台模式下自动启动 Monitor.php。

              <script>
              
               var xmlhttp = new XMLHttpRequest();
                      xmlhttp.onreadystatechange = function() {
                          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
              
                          }
                       }
              
                 xmlhttp.open("GET", "Caller.php", true);
                      xmlhttp.send();   
              
              </script>
              

              所以最后的流程是Parent.html----->Caller.php----->Monitor.php

              【讨论】:

              • 这会在页面加载时无限运行吗?关闭窗口后,系统内存似乎已满,我的系统挂了。
              • 这不是php问题
              猜你喜欢
              • 2017-12-17
              • 2012-09-11
              • 1970-01-01
              • 2014-01-31
              • 2011-01-05
              • 1970-01-01
              相关资源
              最近更新 更多