Scripts do not execute when changing iframe content using innerHTML

I would like to load the contents of an iframe using JavaScript. I do not want to change src, but directly the contents:

document.getElementById('frame').contentDocument.body.innerHTML = data; 

This works, but JavaScript in data not executed. Is this protection or am I forgetting something?

+4
source share
4 answers

It seems that the problem is not with the iframe, but that the scripts are not executed when pasted into the DOM text using innerHTML.

You might want to check the following stack overflow message for several solutions:

+3
source

Use this to get a crossbrowser document

 //returns iframe document function getIFrameDocument(iframe) { var doc; if (iframe.contentDocument) {//FF-Chrome doc = iframe.contentDocument; } else if (iframe.contentWindow) { doc = iframe.contentWindow.document; } else if (iframe.document) {//IE8 doc = iframe.document; } else { doc = window.frames[iframe.id].document; } return doc; } 
+1
source

try it

on the index.html page write:

 <script type="text/javascript"> function init() { var s = document.createElement("script"); s.innerHTML="alert('ops');" document.getElementById("frame").contentDocument.getElementsByTagName("body")[0].appendChild(s); } window.onload = init; </script> 

...

 <body> <form id="form1"> <div> <iframe id="frame" src="test.html"></iframe> </div> </form> </body> 

Then just write test.html as:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> </body> </html> 

and download index.html from the web server and the code works!

0
source

Something like the following will work.

 <iframe id = "testframe" onload = populateIframe(this.id);></iframe> // The following function should be inside a script tag function populateIframe(id) { var text = "This is a Test" var iframe = getObj(id); var doc; if(iframe.contentDocument) { doc = iframe.contentDocument; } else { doc = iframe.contentWindow.document; } doc.body.innerHTML = text; } 
0
source

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


All Articles