1

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();
})
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 1
    Possible duplicate of [getElementById.contentDocument error in IE](http://stackoverflow.com/questions/1477547/getelementbyid-contentdocument-error-in-ie) – Devi Veeramalla Jan 22 '17 at 07:57

1 Answers1

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>
Z-Bone
  • 1,534
  • 1
  • 10
  • 14
  • 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) ? – copenndthagen Jan 23 '17 at 05:17
  • This works for all recent versions as you can see here: https://developer.mozilla.org/en/docs/Web/API/Document/readyState#Browser_compatibility. – Z-Bone Jan 23 '17 at 09:30
  • Hmm..strange...But seems like some issue in Chrome...http://stackoverflow.com/questions/13952942/iframe-readystate-does-not-work-in-chrome – copenndthagen Jan 23 '17 at 10:40
  • They are talking about iframe.readyState , we discussed document.readyState. Just try it for yourself on chrome. – Z-Bone Jan 23 '17 at 10:42
  • 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 – copenndthagen Jan 23 '17 at 10:50
  • So initially in Chrome, it is working without the 2 lines for readystatechange/readyState – copenndthagen Jan 23 '17 at 10:52
  • Just add something like `if (document.readyState) { // Use the eventlistener} else { // don't use }` – Z-Bone Jan 23 '17 at 13:44