Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iframe contentDocument and contentWindow is null

I am trying to access iframe's contentDocument and contentWindow in following code. But they both are null.

    var iframe = document.createElement('iframe');
    this.get__domElement$i().appendChild(iframe);
    if (iframe.contentDocument) {
         iframe.contentDocument.write("Hello");
     }
    else if (iframe.contentWindow) {
         iframe.contentWindow.document.body.innerHTML = "Hello";
     }

Can someone tell me whats wrong in this? Thanks

When i do Document.Body.AppendChild(iframe), then contentDocument and contentWindow are non null.

Can someone tell me whats wrong when i append the iframe to div?

Thanks a lot.

like image 968
prasad mandore Avatar asked Aug 28 '12 19:08

prasad mandore


1 Answers

I know that this is a bit late, but i was researching this and stumbled on your question:

I got the same error as you, because the div i was trying to append the iframe to wasn't loaded yet when i was trying to append the iframe. If the div is loaded your code works:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div id='test' >

        </div>
        <script>
            var iframe = document.createElement('iframe');
            var myDiv = document.getElementById('test');
            myDiv.appendChild(iframe);
            if (iframe.contentDocument) {
                iframe.contentDocument.write("Hello");
            }
            else if (iframe.contentWindow) {
                iframe.contentWindow.document.body.innerHTML = "Hello";
            }
        </script>
    </body>
</html>

Here is a jsFiddle with this working code and another with the tag in the giving an error TypeError: Cannot call method 'appendChild' of null .

like image 66
Filipe Silva Avatar answered Oct 04 '22 02:10

Filipe Silva