为什么iframe.contentWindow == null?

Tim*_*imo 43 html javascript iframe dom

我使用以下代码动态创建iframe.

var iframe_jquery = $("<iframe>")
    .addClass("foo")
    .appendTo(container); // container is a jQuery object containing a <div> which already exists
Run Code Online (Sandbox Code Playgroud)

然后,我想访问其contentWindow,但它是null:

var iframe = iframe_jquery.get(0);
if (iframe){ // iFrame exists
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
}
Run Code Online (Sandbox Code Playgroud)

所以我想:"也许iframe尚未准备好了吗?" 所以我尝试过:

iframe_jquery.ready(function(){
    var iframe = iframe_jquery.get(0);
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
});
Run Code Online (Sandbox Code Playgroud)

结果相同.

怎么了?

Los*_*ear 35

上周我在使用iFrames(构建一个rtf编辑器)时遇到了这个问题,是的,它还没有准备好.

我想如果我把它放在一个.ready()它可以工作,但是.ready()当DOM准备好,而不是当iFrame加载其内容时,所以我最终用jQuery包装我的代码.load().

试试这个:

$(function () {  
    $("#myiframe").load(function () {                        
        frames["myframe"].document.body.innerHTML = htmlValue;
    });
}); 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • load 事件绝对应该起作用...但有时在 Chrome/webkit 中不起作用:( (2认同)

Poi*_*nty 16

问题是,在<iframe>真正添加到页面的实际DOM之前,您将不会"真实". 这是一个小提琴演示..

  • 似乎我无法理解:我可以看到 iframe,那个 iframe 怎么没有添加到实际的 DOM 中? (2认同)

Gab*_*abe 6

根据浏览器的不同,访问document或者<iframe>可能会有所不同.

以下是如何处理它的示例:

if (iframe.contentDocument) // FF Chrome
  doc = iframe.contentDocument;
else if ( iframe.contentWindow ) // IE
  doc = iframe.contentWindow.document;
Run Code Online (Sandbox Code Playgroud)

  • 我认为,`contentWindow`属性几乎无处不在.这是IE的旧版本缺少的`contentDocument`. (5认同)