【问题标题】:Google Auth call back inside custom elementGoogle Auth 在自定义元素内回调
【发布时间】:2018-07-22 16:15:26
【问题描述】:

我正在尝试使用下面的代码将 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>
        `;
        }
    }
);

【问题讨论】:

  • 您是否尝试在 connectedCallback 方法上定义 window.onSignIn = this.onSignIn?
  • window.onSignIn = this.onSignIn.bind(this); 更好

标签: javascript google-authentication custom-element


【解决方案1】:

您还可以按照custom Sign-In button 上的 Google 身份验证文档中的说明明确定义成功回调。

例如:

connectedCallback() {
    console.log("google-auth");

    this.innerHTML = `
        <div id="my-signin2"></div>
    `;

    gapi.signin2.render('my-signin2', {
        'theme': 'dark',
        'onsuccess' : this.onSignIn.bind(this)
    });
}

如果您这样做,则在调用 connectedCallback() 时,Google 库必须已经加载(即:没有 async defer 属性)。

如果您想保留async defer 属性,则必须使用全局render() 函数,该函数将调用自定义元素方法来呈现按钮:

function render() { 
    GA.render() // where GA is the custom element id
}

class extends HTMLElement {
   render() {
       gapi.signin2.render('my-signin2', 
       ...
   }
}

【讨论】:

  • 是的,我也发现了这个,但是当你提供它时,我在 cmets 中恢复了你的解决方案。无论如何,我很感激
猜你喜欢
  • 2017-11-06
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多