Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1230 How can I capture the window close event when the user clicks the window close icon?

irt.org | Knowledge Base | JavaScript | Window | Q1230 [ previous next ]

Q1230 How can I capture the window close event when the user clicks the window close icon?

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.

Feedback on 'Q1230 How can I capture the window close event when the user clicks the window close icon?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.