Katie Shamus
Katie Shamus

Reputation: 61

How to create an iframe from an html code snippet that includes a script tag

I need to create iframes dynamically from a snippet of HTML. I am able to render the html but it seems some of the script tag is not being included.

I am doing this in react and haven't found documentation on the best way to create an iframe dynamically, so I am creating the element on the dom and then removing the element when the component unmounts.

Here is how I am creating the iframe (the following is inside a method I call on componentDidMount)

      const iframe = document.createElement("iframe");
      const html = HTMLblock;
      iframe.id = "iframe";
      iframe.src = "data:text/html;charset=utf-8," + encodeURI(html);
      document.body.appendChild(iframe);

HTMLblock is a snippet of html which has a script tag. The iframe is not rendering properly, as I am getting the following error in my devtools - Query variable sumotoken not found

Any insight greatly appreciated!

Upvotes: 2

Views: 1873

Answers (1)

WillD
WillD

Reputation: 6552

Try using the srcdoc attribute of <iframe>

<iframe id="myframe" srcdoc="My iframe Content <script>console.log('hello')</script>"</iframe>

With your JS:

const iframe = document.createElement("iframe");
const html = 'Iframe Content<script>console.log("hello")<\/script>';
iframe.id = "iframe";
iframe.setAttribute('srcdoc', html);
document.body.appendChild(iframe);

Note: you have to escape the / in the </script> with a \ otherwise it generates an error.

My tests show "hello" in the console.

No IE support through:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/srcdoc

Upvotes: 2

Related Questions