Wednesday, February 27, 2008

Accessing javascript methods from an IFRAME

If you need to access any javascript methods defined in the parent/main webpage from an IFRAME make use of the top property followed by the javascript method name ex. top.myfunction() ; where myfunction() has been defined in the parent/main webpage.


vice-versa to access methods from within an IFRAME in the parent/main webpage, you will need the following syntax:
window.<>.<> ex.window.sub_frame.subpagedisplay(); where sub_frame is the frame ID defined in the parent/main webpage and subpagedisplay() is the javascript function defined in the subpage or in the iframe src property.



NOTE: Both the html files shown below need to be on the same DOMAIN as browsers do NOT allow cross-site scripting.

complete parent/main webpage code: mainHTML.html


<html>
<head>
</head>
<iframe id="sub_frame" name="sub_frame" src="sub_frame.html"></iframe>

<script type="text/javascript"><!--
function myfunction()
{
alert('main page function called');
}

function subpagefn()
{
window.sub_frame.subpagedisplay();
}
//-->
</script>
<body>
main page
<a href="javascript:subpagefn();">call sub page function</a>
</body>
</html>




complete subpage/IFRAME webpage code: sub_frame.html

<html>
<head>
<script type="text/javascript"><!--
function showme()
{
top.myfunction() ;
}

function subpagedisplay()
{
alert('in sub page');
}
//-->
</script>
</head>
<body>
iframe page
<a href="javascript:showme()">some link</a>
</body>
</html>

No comments: