iframe contentDocument和contentWindow为null [英] iframe contentDocument and contentWindow is null

查看:1755
本文介绍了iframe contentDocument和contentWindow为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下代码访问iframe的contentDocument和contentWindow.但是它们都为空.

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

当我执行Document.Body.AppendChild(iframe)时,contentDocument和contentWindow都不为null.

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

当我将iframe附加到div时,有人可以告诉我怎么了吗?

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

非常感谢.

推荐答案

我知道这有点晚了,但是我正在对此进行研究并偶然发现了您的问题:

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

我遇到了与您相同的错误,因为在尝试附加iframe时,我尝试将iframe附加到的div尚未加载.如果加载了div,则您的代码有效:

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>

这是一个 jsFiddle ,其中包含此工作代码和

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 .

这篇关于iframe contentDocument和contentWindow为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆