Iframe contentDocument and contentWindow is null

I am trying to access iframe contentDocument and contentWindow in the following code. But both of them are equal to zero.

var iframe = document.createElement('iframe'); this.get__domElement$i().appendChild(iframe); if (iframe.contentDocument) { iframe.contentDocument.write("Hello"); } else if (iframe.contentWindow) { iframe.contentWindow.document.body.innerHTML = "Hello"; } 

Can someone tell me what's wrong with that? Thanks

When I do Document.Body.AppendChild (iframe), then contentDocument and contentWindow are not null.

Can someone tell me what is wrong when I add an iframe to a div?

Many thanks.

+6
source share
1 answer

I know this is a little late, but I studied this and came across your question:

I got the same error as you, because the div I was trying to add iframe to was not loaded yet, when I was trying to add iframe. If the div is loaded, your code works:

 <!DOCTYPE html> <html> <head> </head> <body> <div id='test' > </div> <script> var iframe = document.createElement('iframe'); var myDiv = document.getElementById('test'); myDiv.appendChild(iframe); if (iframe.contentDocument) { iframe.contentDocument.write("Hello"); } else if (iframe.contentWindow) { iframe.contentWindow.document.body.innerHTML = "Hello"; } </script> </body> </html> 

Here is a jsFiddle with this working code and another with a tag when TypeError: Cannot call method 'appendChild' of null error TypeError: Cannot call method 'appendChild' of null .

+2
source

Source: https://habr.com/ru/post/923994/


All Articles