我需要从 HTML 片段动态创建 iframe。我能够渲染 html,但似乎某些脚本标记未包含在内。
我在 React 中执行此操作,但尚未找到有关动态创建 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
是一个带有 script 标签的 html 片段。 iframe 未正确渲染,因为我在开发工具中收到以下错误 - 未找到查询变量 sumotoken
非常感谢任何见解!
最佳答案
尝试使用srcdoc
<iframe>
的属性
<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>
与 \
否则会产生错误。
我的测试在控制台中显示“hello”。
不支持 IE:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/srcdoc
关于javascript - 如何从包含脚本标记的 html 代码片段创建 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61090367/