首页 > 解决方案 > 使用 JavaScript 的 Google 身份自定义登录

问题描述

通过 Google 登录,我们使用自定义按钮皮肤(遵循https://developers.google.com/identity/sign-in/web/build-button中提到的品牌指南),然后调用手动登录JS 基本上使用这个:

gapi.load('auth2', function(){
    gapi.auth2.init().signIn().then(function(response) {
        // handle success
    }).catch(function(error) {
        // handle error/cancel
    });
});

我正在查看 Google Identity 的文档,但似乎这些(自定义按钮或通过 JS 触发登录)都不可能?有没有办法做到这一点,我错过了?我们真的希望能够使 Google 登录按钮与我们的其他登录按钮保持一致,并处理 UI 友好的大小调整等。非常感谢!

注意:我知道这google.accounts.id.prompt()在文档中,但这似乎并不普遍。当我尝试它时,我只是得到一个opt_out_or_no_session错误,没有任何反应。另外,我们希望使用 Google 按钮,而不是一键,这就是我认为的目的。

标签: javascriptgoogle-signingoogle-identity

解决方案


您可以通过执行以下操作来做到这一点:

const clientLoad = new Promise(resolve => {
  gapi.load('auth2', () => {
    resolve(gapi.auth2.init({ client_id: '<your_client_id>' }));
  });
});

async function login() {
  const client = await clientLoad;
  const response = client.signIn().catch((e) => {
    // in case user closes the popup
    if (e.error === 'popup_closed_by_user') {
      return null;
    }
    throw e;
  });

  // handle your authentication flow with the token received
  console.log(response.getAuthResponse());
}

在您的按钮中:

<button class="your-custom-style" onclick="login()">
  Login with google
</button>

推荐阅读