Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contentDocument.document returning undefined [duplicate]

I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this:

<html>
    <head>
        <script>
            function myFunc(){
                alert("I'm getting this far");
                var doc=document.getElementById("frame").document;
                alert("document is undefined: "+doc);
            }
        </script>
    </head>
    <body>
        <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe>
    </body>
</html>

I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail.

like image 876
Dude Dawg Avatar asked Nov 26 '22 05:11

Dude Dawg


1 Answers

Try the following

var doc=document.getElementById("frame").contentDocument;

// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;

Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.

  • http://help.dottoro.com/ljctglqj.php

Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy

  • http://javascript.info/tutorial/same-origin-security-policy
like image 192
JaredPar Avatar answered Jun 27 '23 00:06

JaredPar