iframe contentDocument and contentWindow is null



我正在以下代码中尝试访问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时出了什么问题吗?

非常感谢。

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

我得到了和您相同的错误,因为当我试图附加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>

下面是一个jsFiddle,其中包含此工作代码,另一个包含中的标记,并给出错误TypeError: Cannot call method 'appendChild' of null

最新更新