捕获浏览器关闭事件

时间:2015-05-28 10:10:58

标签: javascript jquery

我想使用javascript捕获浏览器关闭事件。我用谷歌搜索,但我没有得到任何解决方案,下面是我的代码,我在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>

有没有办法可以捕获浏览器关闭按钮事件,我见过开发人员使用X和Y轴,但不建议大多数开发人员使用。

谢谢..

1 个答案:

答案 0 :(得分:1)

  

您可以尝试此操作..提示用户在关闭标签前确认。你可以做一些你需要的事情

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