There is an iframe present in my HTML as below;
<iframe id="ifrContainer"></iframe>
I want to dynamically append form element inside this iframe. I have the following code to do that;
var iframeContainer = document.getElementById('ifrContainer');
var innerDoc = (iframeContainer.contentDocument) ? iframeContainer.contentDocument : iframeContainer.contentWindow.document;
innerDoc.body.innerHTML += '<form id="myForm"></form>';
The above code works fine in Chrome. But fails in IE.
It is giving error for innerDoc.body.innerHTML (saying it is null)
Not sure what I am doing wrong.
Note: I want to write into the iframe & not read the contents
This is how the function is called in my Ember app (the function has the iframe code)
Ember.run.scheduleOnce('afterRender', this, function() {
this.myIframeFunc();
})
asked Jan 22, 2017 at 7:52
copenndthagen
51.1k106 gold badges316 silver badges494 bronze badges
-
1Possible duplicate of getElementById.contentDocument error in IEDevi Veeramalla– Devi Veeramalla2017年01月22日 07:57:37 +00:00Commented Jan 22, 2017 at 7:57
1 Answer 1
For some reason in IE it is only possible after document.readyState == 'complete'
This works for me in IE.
<iframe id="ifrContainer"></iframe>
<script>
var iframeContainer = document.getElementById('ifrContainer');
var innerDoc = iframeContainer.contentDocument;
document.addEventListener('readystatechange', function() {
if (document.readyState == 'complete') {
innerDoc.body.innerHTML += '<form id="myForm"><input value=1></form>';
}
});
</script>
answered Jan 22, 2017 at 8:40
Z-Bone
1,5841 gold badge10 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
copenndthagen
Great. Thx a lot. So should the readyState check be added without any browser check? I mean will the same code pass for all the browsers (incl Firefox, Chrome) ?
Z-Bone
This works for all recent versions as you can see here: developer.mozilla.org/en/docs/Web/API/Document/….
copenndthagen
Hmm..strange...But seems like some issue in Chrome...stackoverflow.com/questions/13952942/…
Z-Bone
They are talking about iframe.readyState , we discussed document.readyState. Just try it for yourself on chrome.
copenndthagen
It is not working for me in Chrome now..Though I would like to add I am running this code in my Ember app & this code is called inside afterRender i.e. after the rendering is completed...I have added the code by updating my orig question
|
default