Timo Ernst
Timo Ernst

Reputation: 16003

JavaScript nullpointer exception: Why is contentWindow and contentDocument of my dynamically created iFrame always null?

I created a one-page website using jQueryMobile.

"One-page" means the whole website consists of just one index.html file while different content is displayed via anchors, e.g.

I created an iFrame via JavaScript like this:

var iframe = $("<iframe>").addClass("myframe").appendTo(container).get(0);
var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;

In line 2 I get an exception which states:

Uncaught TypeError: Cannot read property 'document' of null

which seems to come from this call:

iframe.contentWindow.document

So, obviously, both iframe.contentWindow as well as iframe.contentDocument are null.

Now here comes the weird part: This only happens on one of the anchors

Example: if I directly jump into the website using URL index.html#start everything works but on index.html#aboutus I get the exception mentioned above.

Please don't ask me what's the difference between both anchors. They're both completely different and I don't know where to start to debug.

Now, my question would be: Why on earth would the code above not work on anchor #aboutus but work on anchor #start?


Update: Some more info for you:

  1. I want to fill in the content for the iframe dynamically without using the src attribute but using the iFrameDoc.write() function instead. As you can see you need the iframe document for this which is null. This approach works perfectly on other anchors but won't work on my one specific anchor "site".

    iframeDoc.open(); iframeDoc.write('Foo'); iframeDoc.close();

  2. I also tried waiting a while until the iframe has loaded.

Still same result

var iframe = $("<iframe>").addClass("myframe").appendTo(container).get(0);
setTimeout(function(){
var iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
}, 3000);

The "load" event isn't even being fired because there was no content written into the iframe yet.

Upvotes: 2

Views: 5731

Answers (1)

Timo Ernst
Timo Ernst

Reputation: 16003

I finally found the source of the problem. The element which was stored in the variable "container" was not properly attached to the DOM tree. That's why the iframe also wasn't part of the dom and no document was created.

Upvotes: 1

Related Questions