WWW FAQs: How do I close the browser window with JavaScript?


2006-09-06: Yes, you can close the browser window with JavaScript code. But if the window was not originally opened by JavaScript code, you won't like the results. Internet Explorer will display an annoying prompt to the user, and Firefox will refuse to close the window at all. So closing windows from JavaScript is most useful if we opened them ourselves in the first place.

That is, to open a window called player that displays the file player.html, you can use code like this (not in player.html itself, but rather in the page the user is coming from):


<script>
function openWindow()
{
  window.open("player.html", "player");
}
</script>
<a href="javascript:openWindow()">Open The Player Window</a>

The window opens when the user clicks on the "Open The Player Window" link. You could call openWindow from other code, but keep in mind that web browser popup blockers - which pretty much everybody has these days - will just ignore it unless you are responding to a mouse click.

Then, in player.html, you can close the player window again with this code:


<script>
function closeWindow()
{
  // Close the current window
  window.close();
}
</script>
<a href="javascript:closeWindow()">Close This Player Window</a>

When the user clicks on "Close This Player Window," the player window "self-destructs."

Once again, this works only when the window being closed was created by JavaScript code in the first place.

When You Have Multiple Frames

Some readers have asked how to close the main window from a frame. As before, you can only do this if the main window was created by JavaScript code.

As long as that's the case, though, you can do it like this:


<script>
function closeTop()
{
  var top = window.open("", "_top");
  top.close();
}
</script>
<a href="javascript:closeTop()">Close This Entire Window</a>

The special window name _top always refers to the outermost parent window, even if you are deep inside a nested frame.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!