As websites get more and more complex,
with the use of pop-up windows to display information to the user, for example,
the ability to refer to these windows explicitly in our scripts becomes
crucial. Let's look at a likely case.
An important point to remember when opening new windows is the need to explicitly
declare the new window name outside of the function that creates it. Below
is an example of this (here we shall call the new window 'LaunchedWin').
var LaunchedWin
function OpenWin()
{ LaunchedWin = window.open("LaunchedWin.html", "LaunchedWin",
"width=300,height=100,toolbar=no,status=no,menubar=no")
}
We can now access this new window, and its contents, using the following
syntax (we'll assume that the document in the new window contains a text
field, 'newText', on a form called 'changeForm').
LaunchedWin.document.changeForm.newText
After opening this new window, you may need to refer to the original
'opener' window from a script in the new window. To achieve this we
use 'window.opener' to return the document that opened the new window. For
example, suppose we have opened our new window by calling our
example function when clicking a button on a form called 'myForm'. From
this newly created window we can refer to this form in the opening window
as follows:
window.opener.document.myForm
We can then extend this to reference any element on this form. Given that
we have a text field on 'myForm' called 'oldText' we could then alter the
text in this field like so:
window.opener.document.myForm.oldText.value = "new text
goes here"
Let's extend our example further. Suppose we have a page containing a text
box and we want to open a new window also containing a text box and
be able to update the contents of either text box from the other window.
To see this in action, launch the new window by clicking 'Launch Window'
below and then enter some text in either text box and click the relevant
'Change Text' button.
As you can see, we now have access to all elements in our windows from within
our scripts. Click 'View Source' in either window to see how we acheived
this (we've just expanded slightly on the examples given earlier in this
article).