I recently had a problem where I was opening a browser window from an e-mail client. After taking a survey, I wanted a button to close this same window. In IE, it was fine to simply use window.close(); to close the window. However, Firefox, the evil genius that it is, will not let you do that because it believes you did not click to open this window in the first place. In order to trick it, you quick load a blank page then close it. The code:

<a href="javascript:window.open('','_parent','');window.close();">
Close this window</a>

So now, when you click the link, it closes the browser window. It works in both IE and Firefox 1.5 (and I believe others as well, but not personally tested). Finding that snippet of code saved me a lot of time! So I hope someone else finds it useful.

Update, May 1 2008:

This code only works on Firefox 1.5 and IE. In Firefox 2.0, Unless a website opened up a window - it can not close it. So, in my case I want to close the window after a user takes a survey, opened from an email window. Firefox 2.0 gives this error: Scripts may not close windows that were not opened by the script. I’m not sure what the right answer is here. They are doing it to prevent malicious scripts from closing windows. But even if they added an option to change that, most users wouldnt have it enabled by default.

So… where does that leave us? Please let me know if anyone knows of code that can close a window with Javascript in Firefox 2.x or 3.x.


This post has 15 comments. Add your own.

Comments

Lorenzo - 08 Nov 06 at 05:23:04

Bravo!!! Funziona.

Balamurugan - 14 Dec 06 at 07:14:37

Doesn’t work in firefox 2.0

Dave - 20 Dec 06 at 13:16:41

Does anyone have a solution to Firefox 2.0 and closing a window with Javascript that does not involve changing Firefox settings?

MH - 07 Mar 07 at 04:59:03

But this trick is not working for FF 2.0.0.2, do you have any work around for this?

Laurie - 02 Oct 07 at 15:41:24

did anyone ever figure out how to write a close window javascript that will work in Firefox 2?

Nikolai - 14 Nov 07 at 02:20:45

This worked perfectly for me with Firefox 2.0.0.9

JohnsonS - 29 Nov 07 at 18:43:01

Not working with Firefox 2.0.0.10

kecik - 03 Dec 07 at 16:34:49

not working with my Firefox 2.0.0.9

Lydia - 27 Feb 08 at 16:18:04

Not working with my Firefox 2.0.0.12.

berkx - 03 Mar 08 at 03:39:07

Not working with firefox v2.0.0.12

jason - 03 Mar 08 at 04:19:22

Not working with firefox v2.0.0.12

tester - 01 May 08 at 08:43:56

Not working with my Firefox v2.0.0.14.

vishal - 09 May 08 at 05:29:04

its not working on FireFox 2.0

forex - 21 May 08 at 11:46:11

under ff 2 you have to set manually under about:config
dom.allow_scripts_to_close_windows to true
then it’ll work

Alexia - 29 May 08 at 04:45:49

Works like a charm! Thanks!!!:)

Trackbacks