How to close a window or tab in FireFox with Javascript

Recently at work I was asked to make javascript:window.close(); work in FireFox. I searched hard and long across numerous forums and on each and every one the answer was the same - it cannot be done unless the page was opened by a script! Or at least it couldn't until I was asked to make it happen :-)

I'm by no means a JavaScript expert - in fact I hardly know any at all - but I couldn't believe that this was completely impossible so I came up with the following:

The first step is to fool the browser into thinking that it was opened with a script...'','_parent','');

This opens a new page, (non-existent), into a target frame/window, (_parent which of course is the window in which the script is executed), and defines parameters such as window size etc, (in this case none are defined as none are needed). Now that the browser thinks a script opened a page we can quickly close it in the standard way...


And there you have it - I told you it was simple! In case you didn't follow that, here is the complete solution in two easy steps:

1. Copy/paste the following code to the head of your page...

<script language="javascript" type="text/javascript">
function closeWindow() {'','_parent','');

2. Set your link like this:

<a href="javascript:closeWindow();">Close Window</a>

Other Experiments

This is actually only my second JavaScript experiment but please feel free to check out a couple of my CSS experiments if you like, where you can also read a little more about me.

  1. Imageless Page: This page is a quick play on making a page look graphical using only CSS and no images.
  2. Color Chooser: An experiment in graphical rollovers with triggers positioned anywhere on a page using only CSS, (and images this time round).

© 2006 Marcos J. Drake - Your New Designer.