Iframed Page Runs JavaScript On Parent Page
A web page may contain an iframe tag. Within the iframe is the content of another web page. The URL of the content displayed within the iframe is different than the URL of the web page with the iframe tag.
The web page with the iframe tag is called the parent page. The web page displayed within the iframe is the child page.
The child page can run JavaScript functions on the parent page – so long as the child page is on the same domain as the parent page.
The trick is to prepend "parent." to the function call.
For example, if the parent page contains code for a function CustomAlertMessage().
A. When the function is called from the parent page (the same page where the code for the function is located), the function is called directly.
CustomAlertMessage("hello at parent");
B. When the function is called from the child page (the page contained within the iframe tag), the function is called with "parent." prepended.
parent.CustomAlertMessage("hello from child");
Here is source code for the two pages comprising a working example.
The code for parent.html:
<html lang="en"> <body> <h1> Parent Page </h1> <script type="text/javascript"> function CustomAlertMessage(s) { alert(s); } </script> <iframe src="child.html" width="200" height="200" frameborder="1"></iframe> <script type="text/javascript"> CustomAlertMessage("hello at parent"); </script> </body> </html>
The code for child.html:
<html lang="en"> <body> <h1> Child Page </h1> <script type="text/javascript"> parent.CustomAlertMessage("hello from child"); </script> </body> </html>
Put both parent.html and child.html into the same directory.
To use the example, load parent.html into a browser. The page parent.html will spawn a "hello at parent" alert box. The page in the iframe (child.html) will spawn a "hello from child" alert box.
(With some browsers, the two alert boxes may displayed on top of each other. With others, first one will be displayed then, after the first has been closed, the other will display.)
To reiterate, to run a JavaScript function located on a parent page from a page loaded within an iframe tag, simply prepend "parent." to the function call. "parent.FunctionName()" instead of "FunctionName()".
However, it will work only when both the parent and the child pages are loaded from the same domain.
Will Bontrager