Javascript – Have JS in iFrame get value from element in main page


This should be an easy one, but im having troubles. I have an iframe that loads an .aspx page. This .aspx page (one in the iframe) has javascript that im using to try and access an element on the main page, but it can never seem to find it.


Here is the .aspx page that loads the iFrame.

<body>    <form id="form1" runat="server">        <div>            <iframe src="myframe.aspx" onload="DoIt();" width="100px" height="100%"></iframe>            <div id='dvT'>hello</div>            </div>    </form></body>

Here is the JS on the iFrame:

<script language="javascript" type="text/javascript">    function DoIt() {        alert(parent.document.getElementById('dvT').innerHTML);    }</script>

I have tried parent.document, this.document, this.contentWindow.document, etc.

The JS must remain on the page loaded in the iFrame.
Any help is appreciated 🙂

Here is the solution

1.) give the iFrame an ID
2.) reference the script in the onload for iFrame via iframeid.methodName
3.) on js in other page, ref via this.parent.document….

Here is the fixed code

<body>        <form id="form1" runat="server">            <div>                <iframe src="myframe.aspx" onload="myFrame1234.DoIt();" width="100px" height="100%" id="myFrame1234"></iframe>                <div id='dvT'>hello</div>                </div>        </form>    </body><!--- SCRIPT ON myframe.aspx page ---><script language="javascript" type="text/javascript">    function DoIt() {        alert(this.parent.document.getElementById('dvT').innerHTML);    }</script>

Best Solution

What are you seeing? When I tried this out (with both pages as plain HTML, not ASPX) nothing happened, because the call to "DoIt()" in the iframe tag onload event doesn't refer to the DoIt() function that is in the inner frame (but is looking for a DoIt() method in the parent. Solution: change iframe src="myframe.aspx" onload="DoIt();" toiframe src="myframe.aspx" onload="contentWindow.DoIt();"