我正在尝试创建一个自定义元素,其中大部分 JavaScript 封装/引用在 template/html 本身中。我怎样才能使模板/元素中的javascript在shadow dom中执行?下面是一个例子,可以更好地理解这个问题。我怎样才能制作脚本template.innerHTML
(<script>alert("hello"); console.log("hello from tpl");</script>
) 执行?
目前我没有收到警报或登录到控制台。我正在用 Chrome 测试这个。
class ViewMedia extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'closed'});
var template = document.createElement( 'template' );
template.innerHTML = '<script>alert("hello"); console.log("hello from tpl")';
shadow.appendChild( document.importNode( template.content, true ) );
}
}
customElements.define('x-view-media', ViewMedia);
<x-view-media />
几点:
- 浏览器不再允许您通过以下方式添加脚本
innerHTML
- DOM Web 组件中没有像 iFrame 那样的脚本沙箱。
您可以使用创建脚本块var el = document.createElement('script');
然后将它们添加为子元素。
class ViewMedia extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'closed'});
const s = document.createElement('script');
s.textContent = 'alert("hello");';
shadow.appendChild(s);
}
}
customElements.define('x-view-media', ViewMedia);
<x-view-media></x-view-media>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)