How do you programmatically close a browser window when you didn't open it? Of course, everybody knows you can't. If they don't know that, they're novice developers and some seasoned veteran will set them straight... gently or otherwise.
Well, this week one of my clients -- whose intranet app opens in a specially formatted window -- told me they didn't want two windows just to start one application. I had very little success removing the toolbars from an existing window, and my vast web development experience told me that I had no other option. Rather, I didn't until a suggestion from a fellow member of the LaTech JavaScript list altered my perspective and resulted in the script I'm about to show you.
All you need to start the magic is to assign a window to the opener property of the current window. If this attribute is not set, the browser will realize that the current window is not open to your manipulation and nothing will happen.
<SCRIPT LANGUAGE="JavaScript">
window.opener = top;
</SCRIPT>
That's all. The following is a list of browsers that either do or don't work with this code. If you don't see your browser below, let me know and I'll add it to the mix.
Browser |
Version |
OS |
Works? |
Internet Explorer |
5.0 |
Windows |
No |
|
5.5 |
Windows |
Yes |
|
6.0 |
Windows |
Yes |
Netscape |
4.6 |
Windows |
Yes |
|
4.79 |
Windows |
No |
|
6.2 |
Windows |
Yes |
|
7.0 |
Windows |
Yes |
Opera |
6.03 |
Windows |
Yes |
|
7.11 |
Windows |
Yes |
OmniWeb |
4.1 |
Mac OS |
Yes |
Mozilla |
1.1 |
Windows |
Yes |
|
1.2.1 |
Windows |
Yes |
|
1.4 |
Windows |
No |
|
1.0 |
Red Hat Linux |
Yes |
Safari |
1.0 |
MacOS |
Yes | |
Before we go further, here are a few warnings: First, use this technique sparingly. It's great for controlled environments, but if you use it in your public sites without telling people first, they probably won't come back to visit. Second, DON'T try the test links below until you bookmark this article. Unless your browser is listed with a "No" above, chances are that the window is about to go bye-bye.
There are two basic ways to use this technique. The first is simply to close the current window, as shown here:
<SCRIPT LANGUAGE="JavaScript">
window.opener = top;
window.close();
</SCRIPT>
Bookmark your spot, and try it here.
Method number two, which I used for my client's intranet app, is to open a new window and then close the old.
<SCRIPT LANGUAGE="JavaScript">
window.open("WhereAmI.asp","newWindow","height=520,
width=730,toolbars=no,scrollbars=yes,resizable=yes");
window.opener = top;
window.close();
</SCRIPT>
Again, be sure you've got that bookmark... and try it here.
Please send all comments, questions, shattered dreams, etc. to the address below. Thanks for reading, and remember that with great power comes great responsibility. Use it wisely, and watch where you swing your webs :)
peterbrunone@aspalliance.com