【问题标题】:Custom Element Web Component Shadow DOM Vendor Scripts/Elements自定义元素 Web 组件 Shadow DOM 供应商脚本/元素
【发布时间】:2018-04-23 21:41:46
【问题描述】:

当使用利用Shadow DOMCustom Elements 时,注入第三方脚本和元素(如Invisible reCAPTCHA)的官方方法是什么,需要这样的脚本:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>` 

要引导 HTML 元素(例如 &lt;button&gt;)并呈现 reCAPTCHA?

shadowRoot 似乎没有head 之类的东西,是不是应该将脚本添加到创建的templateinnerHTML 中?还是通过connectedCallback() 中的appendChild&lt;script&gt; 附加到shadowRoot?在 Shadow DOM 中使用 3rd 方库的官方方法是什么?由于 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) {
    ...
  }
}

感谢您提供的任何指导。

【问题讨论】:

    标签: recaptcha web-component shadow-dom custom-element


    【解决方案1】:

    没有官方方法,因为解决方案依赖于第 3 方库的实现。

    但是,在 reCaptcha 的情况下,解决方法是将 &lt;button&gt; 暴露在普通 DOM 中,并通过 &lt;slot&gt; 元素将其注入 Shadow DOM。

    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>`
            }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多