如何在 shadow dom/web 组件中执行 javascript? [英] How to execute javascript in shadow dom/web components?

查看:46
本文介绍了如何在 shadow dom/web 组件中执行 javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义元素,其中大部分 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);

解决方案

几点:

  1. 浏览器不再允许您通过 innerHTML
  2. 添加脚本
  3. 在 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:

  1. Browsers no longer allow you to add script via innerHTML
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆