iframe contentDocument和contentWindow为null

时间:2012-08-28 19:19:16

标签: javascript iframe

我正在尝试在以下代码中访问iframe的contentDocument和contentWindow。但他们都是空的。

    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";
     }

有人能告诉我这有什么不对吗?感谢

当我执行Document.Body.AppendChild(iframe)时,则contentDocument和contentWindow为非null。

当我将iframe附加到div时,有人能告诉我什么错吗?

非常感谢。

1 个答案:

答案 0 :(得分:2)

我知道这有点晚了,但我正在研究这个问题,偶然发现了你的问题:

我得到了和你一样的错误,因为当我试图追加iframe时,我试图追加iframe的div还没有加载。如果加载了div,则代码可以正常工作:

<!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>

以下是包含此工作代码的jsFiddleanother,其中包含错误TypeError: Cannot call method 'appendChild' of null中的标记。

相关问题