1. Home
  2. Computing & Technology
  3. JavaScript

Window Close

clr gif
Join the Discussion

Questions? Comments?

In my series of articles on popup windows I go into lots of detail on how you can use Javascript to open, manipulate, and close a popup browser window. Information on how to close a popup window is scattered in various tutorials in that series and so for those looking specifically for how to close a popup window I have gathered together all of the different methods here to save you having to hunt through those tutorials looking for it.

The basic rule for being able to close a window using Javascript is that you must have first opened that window using Javascript. The main reason for this is one of security and good manners. Your visitor opened a browser window in order to come and visit your site and you do not have the right or the ability to close that window on them even if you have opened another in the meantime. This is a good thing as closing the browser on someone is a good way to ensure that they wont be back.

You can close windows that you opened using Javascript either from that window itself or from the window that opened it.

To close a window from the window itself you call the following Javascript method:

self.close();

You can also close the window from the same window that opened it. When you call the window.open() method it returns a value that "points" to the new window. By assigning this returned value to a variable we obtain a way to reference that window in order to close it.

var newwin = window.open();
newwin.close();

Another thing that we can do from the page that called the window.open() is to be able to test if the window that was opened has already been closed.

if (newwin && !newwin.closed)

Of course you don't have to use "newwin" as your variable name for referencing the other window, you can assign whatever name you like when you first open the window and so of course you can use multiple values to reference multiple windows that are opened from the same page. Don't go opening too many windows though or you might annoy your visitors. Perhaps you should test that one window has been closed before opening another.

Explore JavaScript

More from About.com

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Windows and Frames
  5. Window Close

©2008 About.com, a part of The New York Times Company.

All rights reserved.