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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With