代码之家  ›  专栏  ›  技术社区  ›  Simon H

自定义元素中的Google Auth回调

  •  0
  • Simon H  · 技术社区  · 7 年前

    我正在尝试使用下面的代码将google auth放入一个自定义元素中它的呈现是正确的,该按钮会触发常规的google auth弹出窗口,但是在完成登录后,不会触发回调-不会触发任何日志,也不会出现错误消息有什么建议吗?

    我猜这和我正在使用一个类有关,因为我在某个地方读到字符串需要引用一个全局函数但在这种情况下这是不可能的

    customElements.define(
        "google-auth",
        class extends HTMLElement {
            constructor() {
                super();
                this._profile = {};
            }
    
            onSignIn(googleUser) {
                var profile = googleUser.getBasicProfile();
                console.log("ID: " + profile.getId()); // Do not send to your backend! Use an ID token instead.
                console.log("Name: " + profile.getName());
                console.log("Image URL: " + profile.getImageUrl());
                console.log("Email: " + profile.getEmail()); // This is null if the 'email' scope is not present.
                this._profile = profile;
            };
    
            connectedCallback() {
                console.log("google-auth");
    
                this.innerHTML = `
                <div class="g-signin2" data-onsuccess="onSignIn"></div>
            `;
            }
        }
    );
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Supersharp    7 年前

    您还可以按照Google Auth文档中关于 custom Sign-In button .

    例如:

    connectedCallback() {
        console.log("google-auth");
    
        this.innerHTML = `
            <div id="my-signin2"></div>
        `;
    
        gapi.signin2.render('my-signin2', {
            'theme': 'dark',
            'onsuccess' : this.onSignIn.bind(this)
        });
    }
    

    如果这样做,Google库必须已经加载(即:没有 async defer 属性)当 connectedCallback() 被称为。

    如果你想保留 异步延迟 属性,则必须使用全局 render() 调用自定义元素方法来呈现按钮的函数:

    function render() { 
        GA.render() // where GA is the custom element id
    }
    
    class extends HTMLElement {
       render() {
           gapi.signin2.render('my-signin2', 
           ...
       }
    }