June 10, 2000 - Parent-Child Window Bidirectional Connection | WebReference

June 10, 2000 - Parent-Child Window Bidirectional Connection

Yehuda Shiran June 10, 2000
Parent-Child Window Bidirectional Connection
Tips: June 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The opener property is very useful, because it completes the bidirectional connection between the opener window and the opened window. Take a look at the following form field:

Enter your favorite tech stock:
Let's see how this works. First, here's the HTML code for the form:
<FORM NAME="stockForm">Enter your favorite tech stock:
<INPUT TYPE="text" NAME="stockBox" SIZE="10" VALUE="">
<INPUT TYPE="button" VALUE="list" onClick="showList()">

Notice that the name of the form is stockForm, while the name of the text field is stockBox. The "list" button launches the showList() function. We have also implemented an onUnload event handler in this tip's <BODY> tag, which invokes the remLink() function. Here's the code for these two functions:

function showList() {
  sList = window.open("stocklist.html", "list", "width=150,height=210");
function remLink() {
  if (window.sList && window.sList.open && !window.sList.closed)
    window.sList.opener = null;

The remLink() function sets the subwindow's opener property to null when the current document unloads. The script in the new window checks the opener property before assigning a value to the text field. We must use this function because the new window's script shouldn't try to access the text box if a different document has been loaded in this window.

Here's the HTML code for stocklist.html:

<TITLE>Stock List</TITLE>
function pick(symbol) {
  if (window.opener && !window.opener.closed)
    window.opener.document.stockForm.stockBox.value = symbol;
// -->
<TR BGCOLOR="#cccccc"><TD><B>NYSE</B></TD><TD><B>NASDAQ</B></TD></TR>
<TR><TD><A HREF="javascript:pick('AOL')">AOL</A></TD>
<TD><A HREF="javascript:pick('CSCO')">CSCO</A></TD></TR>
<TR><TD><A HREF="javascript:pick('CPQ')">CPQ</A></TD>
<TD><A HREF="javascript:pick('INTC')">INTC</A></TD></TR>
<TR><TD><A HREF="javascript:pick('NOK')">NOK</A></TD>
<TD><A HREF="javascript:pick('SUNW')">SUNW</A></TD></TR>
<TR><TD><A HREF="javascript:pick('LU')">LU</A></TD>
<TD><A HREF="javascript:pick('AMZN')">AMZN</A></TD></TR>
<TR><TD><A HREF="javascript:pick('T')">T</A></TD>
<TD><A HREF="javascript:pick('MSFT')">MSFT</A></TD></TR>

For more on windows, go to Tutorial 1, Working with Windows.