Close a subwindow

With JavaScript code, you can close a subwindow when the opener file closes. Here's how.

By Brent Lee Metcalfe

You can close a subwindow when the opener file closes. The code for doing this may be quirky, but it works!

Once you've launched the new widow, click the Reload or Refresh button to close it. The code goes something like this:

var subWin = null;

function popOne() {
  subWin ='yourURL.html','aWin','height=200,width=200');

function eradic8() {
  if (subWin != null && subWin.close();

<body … onUnload="eradic8()">

I know, I know, there's no such thing as a window open property. Tell it to the JavaScript parsers. If you don't include this property, you run the risk of generating an error in 4.x versions of IE and Communicator—especially if the user manually closes the subwindow.

To automatically close a JavaScript-generated window (or windows) when another window is focused, use onFocus to trigger window shutdown instead of onUnload. This is the trick used to close several of the example windows in this article.

Why bother to automatically close windows? Users should not be forced to do more than they have to. If you compel a site visitor to open a new window, you should automatically close the window without user intervention.

Another method

You can also close a subwindow when the opener window object closes. The code for doing this is quite different from the code used in Tip 9, and is Communicator-specific; it doesn't work in IE.

Because the site is a frames-free environment, the example dependent window won't close until the browser is exited.

Since frames are window objects, too, dependent behaves differently with framesets; dependent subwindows launched from a frame will close when the frameset is exited.

Including dependent as a feature in the window open() method lets users automatically close a subwindow when the window object that launched it closes. For example:

function playItAgain() {
  popWin ='aurl.html','win','dependent,resizable,top=20,left=20,height=200,width=200');

Notice that when a new window is specified as a dependent the title font is less bold, and the title bar Navigator icon and minimize and resize buttons are removed.

Non-dependent subwindow:

Dependent subwindow:

Brent Lee Metcalfe is a Web architecture consultant.

Editor's Picks