简体   繁体   中英

Capture browser close event

I want to capture browser close event using 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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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