Javascript create iFrame dom innerHTML

Tags: ,



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?

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"


Source: stackoverflow