如何在 shadow dom/web 组件中执行 javascript? [英] How to execute javascript in shadow dom/web components?
问题描述
我正在尝试创建一个自定义元素,其中大部分 javascript 封装/引用在模板/html 本身中.如何从模板/元素制作要在 shadow dom 中执行的 javascript?下面是一个示例,可以更好地理解该问题.如何从 template.innerHTML
(<script>alert("hello"); console.log("hello from tpl");</script>
代码>) 执行?
目前我没有收到警报或登录到控制台.我正在用 Chrome 测试这个.
class ViewMedia extends HTMLElement {构造函数(){极好的();const shadow = this.attachShadow({mode: 'closed'});var template = document.createElement('模板');template.innerHTML = '<script>alert("hello");console.log("你好,来自 tpl")';shadow.appendChild( document.importNode( template.content, true ) );}}customElements.define('x-view-media', ViewMedia);
几点:
- 浏览器不再允许您通过
innerHTML
添加脚本 - 在 DOM 中没有像 iFrame 中那样的 Web 组件中的脚本沙箱.
<块引用>
您可以使用 var el = document.createElement('script');
创建脚本块,然后将它们添加为子元素.
class ViewMedia extends HTMLElement {构造函数(){极好的();const shadow = this.attachShadow({mode: 'closed'});const s = document.createElement('script');s.textContent = 'alert("你好");';shadow.appendChild(s);}}customElements.define('x-view-media', ViewMedia);
<x-view-media></x-view-media>
I'm trying to create a custom element with most of the javascript encapsulated/referenced in the template/html itself. How can I make that javascript from the template/element to be executed in the shadow dom? Below is an example to better understand the issue. How can I make the script from template.innerHTML
(<script>alert("hello"); console.log("hello from tpl");</script>
) to execute?
Currently I get no alert or logs into the console. I'm testing this with 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 />
A few points:
- Browsers no longer allow you to add script via
innerHTML
- There is no sand-boxing of script within the DOM a web component like there is in an iFrame.
You can create script blocks using
var el = document.createElement('script');
and then adding them as child elements.
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>
这篇关于如何在 shadow dom/web 组件中执行 javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!