自定义元素 Web 组件 Shadow DOM 供应商脚本/元素 [英] Custom Element Web Component Shadow DOM Vendor Scripts/Elements
问题描述
使用自定义元素时Shadow DOM,注入第3方脚本和元素的官方方法是什么,例如隐形 reCAPTCHA 需要以下脚本:
When working with Custom Elements that leverage Shadow DOM, what is the official approach to injecting 3rd party scripts and elements such as Invisible reCAPTCHA which require scripts such:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>`
对于诸如 之类的 HTML 元素要引导并呈现 reCAPTCHA?
for HTML elements such as a <button>
to be leaded and reCAPTCHA to be rendered?
shadowRoot
似乎没有像 head
这样的东西,脚本应该添加到创建的 template
的 中吗?>innerHTML
?还是在 connectedCallback()
中通过 appendChild
将 附加到 shadowRoot?在 Shadow DOM 中使用 3rd 方库的官方方法是什么?由于 Shadow DOM,在包含渲染的自定义元素的页面上加载脚本似乎不会触发渲染.
shadowRoot
doesn't seem to have anything like head
, is the script supposed to be added to the created template
's innerHTML
? Or is a <script>
to be appended to the shadowRoot via appendChild
in connectedCallback()
? What is the official approach to working with 3rd party libraries within Shadow DOM? Loading the script on the page containing the rendered Custom Element doesn't seem to trigger a render due to Shadow DOM.
const template = document.createElement('template');
template.innerHTML = `
<form>
<button class="g-recaptcha"
data-sitekey="your_site_key"
data-callback='onSubmit'>Submit</button>
</form>
`;
class CustomElement extends HTMLElement {
constructor() {
super(); // always call super() first in the ctor.
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
...
}
disconnectedCallback() {
...
}
attributeChangedCallback(attrName, oldVal, newVal) {
...
}
}
感谢您提供的任何指导.
Thank you for any guidance you can provide.
推荐答案
没有官方方法,因为解决方案依赖于 3rd 方库实现.
There's no offical approach because the solution depends on the 3rd party library implementation.
但是,在reCaptcha的情况下,解决方法是将暴露在普通DOM中,并通过
However, in the case of reCaptcha, the workaround is to expose the <button>
in the normal DOM, and inject it in the Shadow DOM via the <slot>
element.
class extends HTMLElement {
constructor() {
super()
this.attachShadow( {mode: 'open'} ).innerHTML= `
<form>
<slot></slot>
</form>`
}
connectedCallback() {
this.innerHTML = `
<button
class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit">Submit</button>`
}
})
这篇关于自定义元素 Web 组件 Shadow DOM 供应商脚本/元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!