May 12, 2000 - Closing Windows
May 12, 2000 Closing Windows Tips: May 2000
Yehuda Shiran, Ph.D.
|
window.close()
method closes the specified browser window. If you call close()
without specifying a window reference, JavaScript closes the current window. With
event handlers, you must specify window.close()
instead of simply using close()
.
Due to the scoping of static objects in JavaScript, a call to close()
without specifying an object name is equivalent to document.close()
.
If you invoke the close()
method on a window that you didn't open with a script, a confirm dialog box
lets the user choose whether the window closes. Navigator doesn't invoke the
dialog box if the window has only one document (the current one) in its session
history. However, if you use close()
to exit the last running instance of the browser, the confirm box pops up (both
browsers).
The following links open a new window with the document tryclose.html. The first link uses JavaScript's window.open()
method to open a window, while the second link simply features a TARGET
attribute:
<A HREF="javascript:void(window.open('tryclose.html'))">Launch Window (with JavaScript)</A><BR>
<A HREF="tryclose.html" TARGET="_blank">Launch Window (with HTML)</A>
The document tryclose.html displays a button that executes the window.close()
method:
<FORM><INPUT TYPE="button" VALUE="Close Window" onClick="window.close()"></FORM>
When you use the first link to open the new window, the browser "remembers" that you opened it with a script. So when you click the button, the new window closes without prompting you to confirm the operation. The second link is a different story. It opens a new window without any JavaScript. When you click the button, Internet Explorer displays the confirm dialog box. However, Navigator immediately closes the window, because the new window doesn't have any other documents in its session history (besides tryclose.html).
For a live demo of these links refer to Tutorial 1.