home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Previous Section Next Section

6.7 Communicating Back to the Main Window

NN 3, IE 3

6.7.1 Problem

You want a script in a subwindow to access variables or document content in the main window.

6.7.2 Solution

With one very early exception (Netscape 2), all scriptable browsers automatically assign an opener property to a window created via the window.open( ) method. Scripts in the subwindow can reach the main window or frame via this opener property. Here is an example of a subwindow script that copies a text box value from the subwindow to a hidden input field in the main window:

opener.document.forms["userData"].age.value = document.forms["entry"].userAge.value;

The opener property references the window or frame whose script executed the window.open( ) method.

6.7.3 Discussion

Any window opened by the user reports that the opener property is null. Therefore, your scripts can test whether the current window was opened by script or manually by comparing the value or type of opener:

if (typeof window.opener =  = "object") {
    // current subwindow opened by script

If the subwindow is opened by a script running inside a frame, the opener property of the subwindow points to the frame holding the document whose window.open( ) method created the window. This means that you can still script your way through the main frameset, if needed. For example a subwindow can access a form value in another frame of the main window frameset with syntax like the following:

opener.parent.frames["prefs"].document.dataForm.colorChoice.value = "#66eeff";

The same-origin security policy observed in access to a subwindow (Recipe 6.6) also applies going in the other direction. If the document in the main window or frame changes to one from a different server and domain, attempted access to details of that document via the opener property fails with security errors.

6.7.4 See Also

Recipe 6.6 to see how scripts in the main window communicate with content in a script-generated window.

    Previous Section Next Section