views:

3722

answers:

2

Hi Guys, I tried following code to get an alert while closing browser window.

<script language="JavaScript" type="text/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>

Its working but if the page contains one hyperlink,clicking on that same alert is coming.I need to show the alert only when i close the browser window and not on clicking hyperlinks.

Duplicate of Java Servlet : How to detect browser closing ? and some other. Just use the search facility... -- PhiLho

+8  A: 

keep your code and, use jquery to handle links.

$(function () {
  $("a").click(function {
    window.onbeforeunload = null;
  });
});
M. Utku ALTINKAYA
+6  A: 

Another implementation is the following you can find it in this webpage: http://amazing-development.com/archives/2008/11/25/javascript-close-hook-for-browser-window/

<html>
  <head>
    <script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save your stuff?"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>
  </head>
  <body>
    <!-- this will ask for confirmation: -->
    <a href="http://google.com"&gt;external link</a>

    <!-- this will go without asking: -->
    <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
  </body>
</html>

What it does is you use a variable as a flag.

netadictos