Search code examples
polymergoogle-authenticationshadow-dompolymer-3.x

Google authentication button not working with shadow dom


I am trying to add google auth button to a simple polymer 3 project, i am following this tutorial: https://developers.google.com/identity/sign-in/web/sign-in?authuser=0

As the tutorial says I am including the Google Platform Library with:

<script src="https://apis.google.com/js/platform.js" async defer></script>

And also i have a div for the button as needed:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

The problem is that i want to have this button inside a web component and the script does not work because it cant see the div that is under shadow DOM(script uses query selector with class name I think). Button works only if its directly in index.js(not under shadow root).

Is there any way to achieve what i need?

Thanks in advance.


Solution

  • If you want to work with Shadow DOM and Google Sign-In, you should put the Google button in the Light DOM to be sure it will be deteced by the Google scripts.

    connectedCallback() {
        this.innerHTML = `<div class="g-signin2" data-onsuccess="onSignIn"></div>`
    }
    

    Then, because the button will be masked by the Shadow DOM, you should implement one of following solutions.

    Option 1: Insert the button in the Shadow DOM

    Use a <slot> element to make the Google Button appear in the Shadow DOM.

    connectedCallback() {
        this.innerHTML = `<div class="g-signin2" data-onsuccess="onSignIn"></div>`
        this.shadowRoot.innerHTML = `Connect with Google: <slot></slot>`
    }
    

    Option 2: Click on the hidden button programmatically

    Create your own <button> in the Shadow DOM and when it is clicked then send a click to the Google button.

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

    NB: Maybe you should not create new Custom Elements with Polymer because this library is not developped any more.