在shadowRoot中执行脚本

问题描述 投票:0回答:1

我正在尝试使用以下代码从shadowRoot中执行脚本。

const template = document.createElement('template');
template.innerHTML = `<script>console.log("hey");</script>`;
this.shadowRoot.appendChild(template.content);

我被告知创建一个template应该工作,但此代码似乎不适用于Chrome v71。

web-component shadow-dom
1个回答
0
投票

要记住的第一件事是影子DOM封装DOM和CSS而不是JavaScript。

第二件要知道的是,你不能通过使用.innerHTML将脚本引入DOM。 See this link。相反,定义组件的类是如何封装JS代码。

虽然你不能使用.innerHTML,你可以创建一个脚本元素并设置其.textContent,然后为此调用.appendChild()

const script = document.createElement('script');
script.textContent = `alert("hey");`;

const el = document.querySelector('.testing');
el.attachShadow({mode:'open'});
el.shadowRoot.appendChild(script);
<div class="testing"></div>

但是,鉴于#2,这可能不是你真正想要做的。

© www.soinside.com 2019 - 2024. All rights reserved.