views:

36

answers:

2

Hello,

I have this HTML code:

<:html:>
 <:head:>
  <:script type="text/javascript":>
   function GetDoc(x)
   {
    return x.document ||
           x.contentDocument ||
           x.contentWindow.document;
   }

   function DoStuff()
   {
    var fr = document.all["myframe"];
    while(fr.ariaBusy) { }
    var doc = GetDoc(fr);
    if (doc == document)
     alert("Bad");
    else 
     alert("Good");
   }
  <:/script:>
 <:/head:>
 <:body:>
  <:iframe id="myframe" src="http://google.com" width="100%" height="100%" onload="DoStuff()" :> <:/iframe:><:/body:><:/html:>

Note that, I replaced every '<' with '<:' and '>' with ':>'.

The problem is that I get message "Bad". That mean that the document of iframe is not got correctly, and what is actualy returned by GetDoc function is the parent document.

I would be thankful, if you told where I do my mistake. (I want to get document hosted in IFrame.)

Thank you.

+2  A: 

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

pkaeding
Huh? That will return either `undefined` (most browsers) or the document that the `<iframe>` element is in (IE), which is precisely the problem the OP wants to fix.
Tim Down
Oops, I guess that's what I get for not testing it first :-/. I just edited it to add the contentWindow reference.
pkaeding
+1  A: 

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

Tim Down
Ok.Now it works fine. Thank you.