In this fourth part of a five-part series that details some of the things you can do with web page dialog boxes, you will learn how to change and add content to the immediate parent box, add a row to a parent dialog box, and much more.
More Tricks with Web Page Dialog Boxes - Executing a Function in Another Window (Page 4 of 5 )
While one dialog box has the focus, you can cause a JavaScript function in another to be executed in that window. To cause another window to execute its own function, you need the reference to the window, followed by a dot and then the name of the function. Now we shall see how to do this.
The DOM allows us to reference the immediate child or immediate parent from the current window. It does not give us a way to reference ancestor or descendant windows. Let us see how to solve our problem for the immediate child and the immediate parent.
Consider the following function in the parent dialog box.
<html>
<head>
<title>Page 2</title>
<script type="text/javascript">
function execChild()
{
window3.execHereChild();
}
function execHereParent()
{
alert('Result from the Parent');
}
</script>
</head>
<body>
<button type="button" onclick="execChild()">Execute in Child</button>
</html>
When you click the button, it calls the “execChild()” function. This function causes the following statement to be executed:
window3.execHereChild();
In this statement, “window3” is the reference to the immediate child’s window. It was obtained when the child window was created. I have not shown that code here. Consider the following code, which is similar to the above code:
<html>
<head>
<title>Page 3</title>
<script type="text/javascript">
function execHereChild()
{
alert('Result from Child');
}
function execParent()
{
parentWin = window.opener;
parentWin.execHereParent();
}
</script>
</head>
<body>
<button type="button" onclick="execParent()">Execute in Parent</button>
</body>
</html>
When you click the button, it calls the “execParent()” function. This function causes the following two statements to be executed:
parentWin = window.opener;
parentWin.execHereParent();
The first line develops the reference to the immediate parent. The second line causes a function in the parent dialog box to be executed.