Search code examples
javascriptiframeinnerhtmltiming

Unable to set value of the property 'innerHTML': timing issue?


Others have encountered a similar error, usually because they tried to access a DOM object before a web page had completely loaded. I am doing something different, but I may also have a timing problem.

I have a Javascript application that communicates with CGI scripts with forms and iframes. The first time the user clicks a submit button, the JS application creates an invisible iframe and sends the form's data to the server. The server is supposed to respond by sending data to the iframe which the JS application reads and interprets.

Here is a very simplified version of the code:

var iframe = document.createElement("iframe");
iframe.name = "myIframe";
document.body.appendChild(iframe);
var iframeDocument = 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
iframeDocument.body.innerHTML = "";

The full error is: TypeError: Unable to set value of the property 'innerHTML': object is null or undefined

The entire page loaded long ago--when the code above executes, the user has entered some data and hit a submit button. However, the iframe is new.

The code works fine on my computer--I cannot reproduce the problem. I can see from a log file on the server that the user agent is 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'.

Perhaps naively, I thought that the iframe had been created and I could set its document's innerHTML property. Could this be a timing problem? Do I have to wait before setting innerHTML, or is something else going wrong?

If the error is indeed caused by a timing problem, I can probably fix it by creating the iframe when the page first loads. If the user then clicks a cancel button, the iframe will never be used--I thought it was better to create the iframe only when it is needed. To really fix this error, I have to understand it--that is why I am asking my question.


Solution

  • Maybe it's a timing issue, you can try :

    var iframe = document.createElement("iframe"),
        iframeDocument;
    iframe.name = "myIframe";
    
    iframe.onload = function(){
        iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
        iframeDocument.body.innerHTML = "";
    };
    
    document.body.appendChild(iframe);    
    

    That way you'll be sure that your iframe will be ready