Trapping close of IE window in ASP.NET

Trap window close event for IE browser
Let's say you want to trap the window close event for the web browser
so that you can give a confirmation dialog asking if the user is sure
to leave the page.The problem is that there is no onclose event for the
window object.The closest event might be onunload since it fires immediately
before the window object is unloaded. However, when the onunload event fires
it is too late to display a JavaScript alert. Therefore, we need an event that
fires prior to a page being  unloaded, which is onbeforeunload.
Define onbeforeunload event in your page <BODY> element as follows:

<BODY onbeforeunload="HandleOnClose()">

Then, add the following JavaScript code into the <HEAD> section of your
ASPX page:


<script type="text/javascript">
       function HandleOnClose() {
           if (event.clientY < 0) {
               event.returnValue = 'Are you sure you want to leave the page?';
           }
       } 
       
   </script>
The trick here is to check clientY property of the event object, which is used to set or retrieve the y-coordinate of the mouse pointer's position relative to the client area of the window, excluding window decorations and scroll bars. This way, you can detect if the user clicked on X button to close the page, or clicked on Refresh button to refresh the page, etc. This approach does not handle key events such as Alt-F4 that lets the user close the window by using the keyboard. You have to handle keyboard events separately
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>

  <script type="text/javascript">
      function HandleOnClose() {
          if (event.clientY < 0) {
              event.returnValue = 'Are you sure you want to leave the page?';
          }
      }
     
  </script>

</head>
<body  onbeforeunload="return HandleOnClose()">
</body>
</html>

No comments:

Post a Comment