我正在尝试将google auth按钮添加到一个简单的聚合物3项目中,我正在按照本教程:https://developers.google.com/identity/sign-in/web/sign-in?authuser=0
正如教程所说,我将谷歌平台库包括在内:
<script src="https://apis.google.com/js/platform.js" async defer></script>
而且我还需要按钮的div:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
问题是我想在Web组件中使用此按钮,并且脚本不起作用,因为它无法看到阴影DOM下的div(脚本使用带有类名的查询选择器,我认为)。 Button仅在其直接位于index.js(不在阴影根下)时才起作用。
有没有办法实现我的需要?
提前致谢。
如果您想使用Shadow DOM和Google Sign-In,您应该将Google按钮放在Light DOM中,以确保它会被Google脚本检测到。
connectedCallback() {
this.innerHTML = `<div class="g-signin2" data-onsuccess="onSignIn"></div>`
}
然后,因为该按钮将被Shadow DOM屏蔽,您应该实现以下解决方案之一。
选项1:在Shadow DOM中插入按钮
使用<slot>
元素使Google Button出现在Shadow DOM中。
connectedCallback() {
this.innerHTML = `<div class="g-signin2" data-onsuccess="onSignIn"></div>`
this.shadowRoot.innerHTML = `Connect with Google: <slot></slot>`
}
选项2:以编程方式单击隐藏按钮
在Shadow DOM中创建自己的<button>
,点击它后点击Google按钮。
connectedCallback() {
this.innerHTML = `<div class="g-signin2" data-onsuccess="onSignIn"></div>`
this.shadowRoot.innerHTML = `<button>Connect with Google</button>`
this.shadowRoot.querySelector( 'button' ).onclick = () =>
this.querySelector( '.g-signin2 .abcRioButtonContentWrapper' ).click()
}
注意:也许你不应该用Polymer创建新的自定义元素,因为这个库不再开发了。