繁体   English   中英

如何从包含脚本标签的 html 代码片段创建 iframe

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

我需要从 HTML 的片段动态创建 iframe。 我能够渲染 html 但似乎某些脚本标签不包括在内。

我在反应中这样做并且没有找到关于动态创建 iframe 的最佳方法的文档,所以我在 dom 上创建元素,然后在组件卸载时删除元素。

这是我创建 iframe 的方式(以下是我在 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是 html 的一个片段,它有一个脚本标签。 iframe 渲染不正确,因为我的开发工具中出现以下错误 - Query variable sumotoken not found

任何见解都非常感谢!

尝试使用<iframe>srcdoc属性

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

用你的 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);

注意:您必须使用\ / </script>产生错误。

我的测试在控制台中显示“你好”。

通过以下方式不支持 IE:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM