Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  123] [ 7]  / answers: 1 / hits: 110571  / 13 Years ago, tue, september 27, 2011, 12:00:00

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.


More From » dom

 Answers
68

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




[#89892] Monday, September 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiejarretk

Total Points: 612
Total Questions: 103
Total Answers: 88

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;