我需要在同一页面上同时使用“使用谷歌登录”和“使用谷歌注册”按钮

I need both "log in with Google" and "sign up with Google" buttons on the same page

本文关键字:谷歌 按钮 注册 登录 一页      更新时间:2023-09-26

努力理解如何实现这一目标,尽管这在网络上非常普遍。

我有两种模式,一种是"注册"模式,另一种是"登录"模式。我需要能够通过用户的 Google 帐户执行这两项操作。我正在通过谷歌API成功创建和登录用户。

麻烦在于谷歌的插入按钮会自动让用户登录。

在页面上,我有:

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

后来:

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

显然,这两个按钮具有不同的onsuccess功能,但是在用户登录时都会调用这两个按钮。我通过仅通过单击按钮实际获取Google脚本来缓解问题:

$('a#google-login').click(function() {
    $.getScript('https://apis.google.com/js/platform.js');
})

但是整个设置的行为并不理想。是否有常见的解决方法?如果用户登录(例如没有任何用户操作),Google会自动运行onsuccess功能,这似乎令人非常沮丧。如果按钮在没有用户操作的情况下运行,那么拥有按钮有什么意义?

所以:我希望能够通过谷歌登录用户,也可以通过谷歌注册用户,但前提是用户实际点击了一个按钮,在这两种情况下。

您可以通过使用命令式方法实现 Google 登录按钮来实现您想要的目标。我的建议是使用自定义按钮。这样,您就可以更好地控制 API。查看此文档:
https://developers.google.com/identity/sign-in/web/build-button

这个视频也可能有所帮助。
https://www.youtube.com/watch?v=Oy5F9h5JqEU]

下面是一个示例代码
https://github.com/GoogleChrome/google-sign-in

正如@agektmr所说,我使用了此处所述的自定义按钮 https://developers.google.com/identity/sign-in/web/build-button

之后,您可以创建 2 个按钮,并为每个按钮使用不同的回调。

这是我在 react 组件中使用的代码,所以这就是我从窗口对象引用 auth2 的原因,但如果你使用香草 JS,你可能不需要它,这也包含一些 ES6,所以很抱歉,如果你不使用 ES6,你可以() => {}转换为 function () { } let转换为var

// This method is from the above cited article, I have just altered it slightly so 
// that you can input a success  callback as a parameter rather than hard coding just one
function attachElementToCallback(element, success) {         
  window.auth2.attachClickHandler(element, {}, success    
    , (error) => {
      var message = JSON.stringify(error, undefined, 2);
      alert(message)
    });
}
function initializeGoogleStuff() {
  window.gapi.load('auth2', () => {
    window.auth2 = window.gapi.auth2.init({
      prompt: "select_account",
    })
    let signInElement = window.document.getElementById("signInButton")
    if (signInElement) {
      attachElementToCallback(signInElement, handleLogin)
    }
    let signUpElement = window.document.getElementById("signUpButton")
    if (signUpElement) {
      attachElementToCallback(signUpElement, (response) => console.log(response))
    }
  })
}

对于 HTML(这只是从上面的文章中复制和粘贴并复制的,如果您想使其符合 Google 的品牌指南,它们具有 CSS 和进一步的说明(如果您希望他们验证您的应用程序,这是必须的)https://developers.google.com/identity/branding-guidelines

<div id="signInButton" class="customGPlusSignIn">
  <span class="icon"></span>
  <span class="buttonText">Sign In</span>
</div>
<div id="signUpButton" class="customGPlusSignIn">
  <span class="icon"></span>
  <span class="buttonText">Sign Up</span>
</div>