1

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.

ie:

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>
schmoopy
  • 6,419
  • 11
  • 54
  • 89

2 Answers2

1

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();" to iframe src="myframe.aspx" onload="contentWindow.DoIt();"

Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
  • Hey thanks - it was actually a combination of things but i was assumming it wasnt just finding the object - it was not finding the object + not finding the script - solution above :-) – schmoopy Sep 16 '09 at 17:40
  • Whoops -- just fixed a type; I had typed "contentWindowDoIt()" instead of "contentWindow.DoIt()". Anyway, if you wanted to skip putting an ID on the iFrame, you can call "contentWindow.DoIt()" in the onload attribute. – Jacob Mattison Sep 16 '09 at 17:48
0

you probably need to walk up the tree using parent.parent or window.top - since your iframe is from the same server, the security model should let you do this.

Henry Troup
  • 180
  • 5