Skip to content
Advertisement

Javascript create iFrame dom innerHTML

gives Error: Uncaught TypeError: Cannot read property ‘body’ of undefined

var f = document.createElement("iframe");
f.id = "s";
f.contentWindow.document.body.innerHTML = "body";

how can i fix this?

Advertisement

Answer

to add content to iframe, you should pass by src attribute, here is an example.

var iframe = document.createElement('iframe'); 
var html = '<body>Foo</body>'; 
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); document.body.appendChild(iframe);

if your content is url, you put it directly into src,like this

iframe.src="https://www.w3schools.com"
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement