Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is iframe.contentWindow == null?

I use the following code to dynamically create an iframe.

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

Then, I want to access its contentWindow, but it's null:

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

So I thought: "Maybe the iframe isn't ready yet?" So I tried:

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

Same result.

What's wrong?

like image 983
Timo Ernst Avatar asked Aug 30 '12 14:08

Timo Ernst


2 Answers

I had this problem last week while playing with iframes (building an rtf editor), and yeah it's not ready yet.

I thought if I put it in a .ready(), it would work, but .ready() is when the DOM is ready, not when the iframe has loaded its contents, so I ended up wrapping my code with jQuery .load().

So try this:

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

Hope this helps

like image 55
Losbear Avatar answered Sep 20 '22 05:09

Losbear


The problem is that your <iframe> won't be "real" until it's really added to the actual DOM for the page. Here is a fiddle to demonstrate..

like image 36
Pointy Avatar answered Sep 19 '22 05:09

Pointy