Question

I'm having trouble accessing the DOM of an iframe content document if I create the iframe dynamically in JavaScript rather than hard-coding it in the HTML.

I'm finding this so far testing in Mac FF26 and Safari 6. It is a local iframe document on the desktop, so there should be no cross-domain issues.

The iframe I generate appears normally in the browser window. But trying to access it with contentDocument, the body element seems to be empty.

Is this a known issue? Perhaps I'm generating my iframe in an unusual way:

var newIframe = document.createElement("iframe");
newIframe.id = "generatedIframe";
newIframe.src = "test.html";
document.body.appendChild(newIframe);
var iframeTag = document.getElementById("generatedIframe");


// the iframe will be appearing normally in the browser now


// but this fails -- innerHTML is empty string:

var iframeContent = iframeTag.contentDocument.getElementsByTagName("body")[0].innerHTML;

// same reference code works if the iframe is hard-coded in HTML instead
Was it helpful?

Solution

In fact your problem is not the way you generated your iframe.

The iframe DOM is only available after it has been loaded.

The code behind illustrates what I mean :

In your parent window container :

<script>
    function doSomething() { alert(iframeTag.contentDocument.getElementsByTagName("body")[0].innerHTML()); }
</script>

In your iframe document

<body onload="window.parent.doSomething();"></body>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top