We help IT Professionals succeed at work.

Capturing the browser close event.

SewellM asked
I need to be able to capture the event when a user closes their browser (by selecting the X or a file>>close).  I am only concerned with IE, so if it IE specific, its OK.  I have looked at the onUnLoad() event and the onBeforeUnLoad(), but these fire when you go to another page and even refresh.  I need something that will capture the browser being closed and fire an event.  The event will basically open a browser window and run a script.

I have looked around, and can find nothing referring to this.  Is there a way to accomplish this? and if not, why not?

Watch Question

You can never know for sure whether the window has closed or not. I am sorry but that is just the way it is.

The only way that can do what you want is to use a new window without a locationbar (meaning that the user cannot go to another location by typing it in there). next thing you would need to do is load a page in that newly opened window with a frameset. That frameset can contain an onunload event which will fire (or onbeforeunload, whatever suits you best). the onbeforeunload or onunload event will only fire once the frameset is being unloaded. Which can only happen in this cvase if the window is being closed.

Here's a sample.

Open a new window without locationbar etc.:
var w = window.open("framesetpage.htm", "", "location=no");

The framesetpage.htm:
 <frameset rows="*,0" onbeforeunload="alert('onbeforeunload')">
  <frame src="index.htm">
  <frame src="blank.htm">


The following coding works well...
I tried this in IE5.5.

<script language="javascript">
function testClose()
     var strTemp=confirm("Do u want to close this window?");

<body onunload="testClose();">


Thanks, but that does not work.  The onUnload event fires under several circumstances.  Yes, one of them is when you try to close the browser, but it also fires when you navigate away from the page you are on.  This event fires when you unload the current event from the browser period.  Select a link, choose an item from your favorites, type in a new URL, all of these fire the onUnLoad event.  This site has in excess of 300+ pages on it, and the user can not select OK everytime they navigate to a new page.

Thanks though.

Anyone have anything else?  I know CJ S probably has THE answer. But since I can not impliment his answer, I can only hope.  



Well, no one else seems to have a better answer, so I guess this is law.  Thanks for the help.


Explore More ContentExplore courses, solutions, and other research materials related to this topic.