How to prevent closing browser window?

user42348 picture user42348 · Dec 2, 2008 · Viewed 79.6k times · Source

I tried the following code to get an alert upon closing a browser window:

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?";
}

It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert. I need to show the alert only when I close the browser window and not upon clicking hyperlinks.

Answer

netadictos picture netadictos · Dec 2, 2008

Another implementation is the following you can find it in this webpage: http://ujap.de/index.php/view/JavascriptCloseHook

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