Wednesday, 5 May 2010

How to prevent Browser Close



First, some clarifications of my requirements:

  1. To prevent the user from closing browser or tab (both are treated similarly).
  2. Note that browser close is different from browser exit. Browser close is done using the "X" button, while browser exit is done using File>Close or Alt+F4 keys.
  3. JS can only catch browser close event.
  4. URL refresh was also to be treated as close.
  5. However, navigation using anchor, buttons or any other DHTML was to be ignored.
  6. Tested on IE8 and Firefox 3.5.

Solution:
  • Directly using event onUnload doesn't help.
  • So found this event and in that checked for the location of click. If location <= 0, it means unLoad has happened outside the browser render area (i.e. unload is happening not because of some link or button). Hence such unloads are due to close or refresh. So prevent them.
  • Preventing them by just returning false or calling stopPropagation() or preventDefault() or stopBubble() doesn't help.
  • Hence this way of setting returnValue.

Code:


  


<script type="text/javascript">
window.onbeforeunload = function ConfirmClose(foEvent)   {
/* For Firefox */
if (foEvent && foEvent.explicitOriginalTarget.clientLeft==0)
foEvent.returnValue = "Fazeel";

/* For IE */
else if (event.clientY < 0) { event.returnValue = "Our Message"; } } </script>





  

  
      

Navigate away!

      Google
  

No comments:

Post a Comment