Closing Windows and Confirmation Boxes
Ever notice how a script that attempts to close a window will at times generate a confirmation and other times not?
to be closed without asking the user for permission via a confirmation box
. In other words, scripts cannot close a main window unconditionally
To close a window unconditionally, a privilege called UniversalBrowserWrite
is needed. Without the privilege, the window.close() method will close only sub windows without asking the user's permission first.
Again, the one exception has to do with main windows - if the main window has only one entry in its session history, the close is allowed without the confirmation.
Before rushing to the work-around, be sure you understand the conditions for an unconditional and conditional closure. Test your current window by clicking the window.close() link below. If your current window has more than one page in its history and was not
NOTE: Explorer for Mac, Netscape 6 and Opera DO allow closure of a main window via the close() mehtod without a confirmation.
, the sub window can be closed via scripting unconditionally.
See it in action
This script generates a sub window that closes itself by using the close() method as the setTimeOut's
The MSIE Work Around
To determine whether or not a window is a main window, Internet Explorer checks to see if the window has an opener. Since windows that have openers can be closed unconditionally, the solution is to make Explorer think
a main window has an opener. That is accomplished by giving a phantom opener a value, in this case, an empty string:
window.opener = ''
To give a sub window's opener a phantom opener, give its opener's phantom opener a value:
window.opener.opener = ''
So to close a main window from a script its document contains:
And to close a main window from a sub window:
First, launch a sub window.
The function could also be invoked when the sub window is closed, so that both are closed at the same time:
<body onunload="window.opener.opener=''; window.opener.close()">
Work Around Variations
Another way to trick IE into thinking a main window is a sub window is to set the phantom opener to "null" (tip from Jim Porath). Setting it to "top" will also work even when the main window is not a frameset.
View the Source