Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

Q98 How can do you close a child window when your site is unloaded from the parent window?

You are here: irt.org | FAQ | JavaScript | Window | Q98 [ previous next ]

Normally you close a child window using an onUnload event handler in the body tag of the window that creates the child window, e.g.:

<body onUnload="childWindowName.close()">

This will however close the child window even if you are just navigating to another page in your site. Keeping it open whilst still within your site is going to more difficult.

What you could do is use the onUnload event handler to trigger a checking mechansim in the child window that checks the location of the newly loaded document in the main window. If its on your own server then you'll be able to check the location, if its not on your server you'll not be able to check the location, and you'll get an error. You may be able to trap this error and thus close the window using self.close().

You'll need to trigger a checking mechanism that will allow a delay for the main window to change its location, so something like:

<body onUnload="childWindowName.functionName()">

And then in the child window:

<script language="JavaScript"><!--
functionName() {
    setTimeout("checkparent()",2000); // a 2 second delay

function closeWindow() {

function checkparent() {
    self.onerror = closeWindow;
    parentWindow = opener.location.href;

Note, that this has not been tested, and will need further work to make it robust. The onerror event handler was only introduced in Netscape 3 (I'm not sure about Internet Explorer). Also you may need to check if the location of the main window, although still on the same server, has not actually gone onto another site on the same ISP

Feedback on 'Q98 How can do you close a child window when your site is unloaded from the parent window?'

©2018 Martin Webb