Home > Software design >  JavaScript within <script> tags are not being executed in an iframe
JavaScript within <script> tags are not being executed in an iframe

Time:01-21

I am building a simple online HTML IDE where students can type HTML into a codemirror editor and then when a button is clicked, the HTML is placed in an iframe to render the page.

My code in question:

function runit() { 
   var prog = myCodeMirror.getValue(); 
   var mypre = document.getElementById("output");
   mypre.contentDocument.body.outerHTML = prog; 
 
}

prog is the html from the editor, mypre is the iframe.

All html placed within <body> tags is correctly executed in the iframe. All css code placed within <style> tags is correctly executed in the iframe. However, any javascript placed within <script> tags is not executed in the iframe.

How can I get <script> tag contents to be correctly executed in the iframe?

CodePudding user response:

This may help:

const runit = () => document.getElementById("output").srcdoc = myCodeMirror.getValue();

We use the property srcdoc to change the content in the iframe as HTML

  •  Tags:  
  • Related