我想将自定义元素定义添加到我的 iFrame。
在主浏览器窗口中,定义工作得很好:
customElements.define("自定义标签", customTag)
然后,将定义移至 iFrame 后,我收到 DOMException:不支持操作
。该功能有但不支持。
iFrame.contentWindow.customElements.define("自定义标签", customTag);
这有什么特殊原因吗?定义自定义标记是否被设计阻止在 iFrame 中并且无法解决,或者我应该在 iFrame 配置中包含某些内容以允许这种“不安全”行为?
最佳答案
如果您想将主 HTML 文档中的自定义元素注入(inject) <iframe>
元素,您可以将其添加到 <script>
内元素。
例如,通过srcdoc
属性:
frame.srcdoc = `
<script>
class customTag extends HTMLElement {
constructor() {
super()
this.attachShadow( { mode: 'open' } )
.innerHTML = "Hello World"
}
}
customElements.define( 'custom-tag', customTag )
<\/script>
<custom-tag></custom-tag>
`
<iframe id=frame></iframe>
注意转义字符\
进入结局</script>
标签。
关于javascript - 在 iFrame 中定义 customElements 会抛出 "DOMException: Operation not supported"。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53612842/