Testing a Main Window's Closed Property from a 2nd Sub Window (opener.opener.closed)

Scenario: a main window (parent window) opens a pop-up window (1st Sub). The 1st Sub then opens another pop-up window (2nd Sub). From the 2nd Sub, we've scripted an action that is to occur in the main window (parent window).

No problem, just refer to the parent window like so:
That is indeed a valid reference to the main parent window. But what if the main parent window or the 1st Sub has been closed? You'd think that by testing the closed property of the parent window would keep any errors from being generated:
if(!opener.opener.closed) { // if opener.opener.closed is false
Now we've got a problem and it is this: sub windows do not have a parent-child relationship like framesets do with their frame source documents. What this means to us is that if either the Main parent window or 1st Sub window is closed, there is no longer any connection between the 2nd Sub and the original Main window. The above statement will cause an error because as far as the JavaScript engine is concerned, opener.opener no longer exists when either the main or 1st Sub window has been closed.

The Fix
Fortunately there is a solution. Simply by storing in a global variable within the 2nd Sub a reference to the Main parent window, a connection to that window is kept alive. In a 2nd Sub (the 3rd window), the following script will attempt to write to a main window, first checking the closed property to see if it still exists.
var mainWin = opener.opener // store reference to main window in global variable

function writeToMain(){

mainWin.document.write("I'm still open, so you can write to me")
// must "close the stream" after writing to NN windows if page has loaded (different than window.close())
alert("Sorry, the main has been closed")
The same technique can be applied to a main window that happens to be a frameset document, as long as it is referenced correctly:
var mainWin = opener.opener.top
For more on frames, see the frames tutorial.

View the Source


View Source | Home | Contact