Closing a window

JavaScript FAQ | JavaScript Windows FAQ  

Question: How do I close a window?

Answer: To close a window that you previously opened from your script, you can use the window.close() method, for example:


where winRef is the window reference, as returned by the method. The gotcha here is that the window referenced by winRef does not necessarily exist at the time when your script attempts to close it. (The user might have closed it already!) And if the window no longer exists, your script may cause errors. Possible workarounds are the following:

  • Place the window-closing code only in the window to be closed. In this case the window reference will be self, and the code will be self.close().
  • Use window.closed to check if the window is still open - before attempting to close it.

If your script tries to execute window.close() for the main browser window that was opened by the user, most browsers will first invoke a dialog asking the user whether to let the script close the browser window. The exact behavior will depend on the user's actual browser, OS, and current settings; here is this dialog as seen in IE8 under Windows XP (Windows Classic UI theme):

Test this yourself: here is a script that attempts to close your browser window.

Copyright © 1999-2011,