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?

Here's why: IE for windows and NN 4.x browsers do not allow a non-JavaScript-generated window with more than one page in its history 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 created using JavaScript, a confirmation box will be generated. Otherwise, the window will close as soon as the close() method is invoked.

NOTE: Explorer for Mac, Netscape 6 and Opera DO allow closure of a main window via the close() mehtod without a confirmation.
<a href="javascript:window.close()">window.close()</a>
If a JavaScript generates a new window, known as a sub window, 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 parameter. Visit the Strings and the Write Method Lesson for info on writing JavaScript WITH JavaScript.

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:
<a href="javascript: window.opener=''; window.close();">Close Main Window without Confirmation</a>
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


 


View Source | Home | Contact