最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - iframe contentDocument and contentWindow is null - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited May 12, 2014 at 11:33 user1804599 asked Aug 28, 2012 at 19:19 prasad mandoreprasad mandore 731 gold badge1 silver badge9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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 .

发布评论

评论列表(0)

  1. 暂无评论