You are here: irt.org | FAQ | JavaScript | Window | Q1230 [ previous next ]
The onUnload event is the one to use.
To capture the close you need to set a flag on all links telling the browser that you are just leaving the page, not closing:
<body onLoad="closing=true" onUnload="if (closing) window.open('thanksForVisiting.html','newwin');"> <a href="nextpage.htm" onClick="closing=false">Click to go to another page..</a>
Leave out the onClick on external links if you want to treat leaving your site as a close.
Note! Do not expect the page to be available to a function in the onUnload! So if you try to read the contents of a form on the page in the browser that is closing, you might get JavaScript errors.
In Microsoft Internet Explorer 4+ (but not Netscape Navigator) you can use the onBeforeUnload event to do whatever you want. Setting the event return value to any non-blank value in the onBeforeUnload will trigger a 'Are you sure your want to leave?' dialogue.
In Netscape Navigator the onLoad event is notoriously unreliable.