简体   繁体   English

捕获浏览器关闭事件

[英]Capture browser close event

I want to capture browser close event using javascript. 我想使用JavaScript捕获浏览器关闭事件。 I googled but I am not getting any solution anywhere,below is my code where I have handled anchor, Form Submit and Submit button on onbeforeunload. 我用谷歌搜索,但是到处都找不到任何解决方案,下面是我在onbeforeunload处理锚,表单提交和提交按钮的代码。

<script>
var validNavigation = false;
function wireUpEvents() {
   window.onbeforeunload = function() {
    if (!validNavigation) {
      // invalidate session
    }
  }

   // Attach the event keypress to exclude the F5 refresh
   $(document).bind('keydown', 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>

Is there any way I can capture browser close button event, I have seen developers using X and Y axis but that is not recommended most of developers. 有什么方法可以捕获浏览器关闭按钮事件,我已经看到开发人员使用X和Y轴,但是大多数开发人员不建议这样做。

Thanks.. 谢谢..

You can try this .. prompting user to confirm before closing tab. 您可以尝试此..提示用户在关闭标签页之前进行确认。 and you can do some thing you need 你可以做你需要的事情

<script language="JavaScript">
      window.onbeforeunload = confirmExit;
      function confirmExit()
      {
        return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
      }
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM