Google API登录按钮:基本v.自定义

EB *_*udd 6 google-api oauth-2.0 google-oauth

我正在努力为网站添加Google登录按钮.在文档中,Google提供了两个选项,即"基本"按钮:

https://developers.google.com/identity/sign-in/web/sign-in

和一个"自定义"按钮使用signin2.render():

https://developers.google.com/identity/sign-in/web/build-button

我遇到的问题是两个按钮表现出不同的行为.如果我使用任一按钮登录,则按钮的"标题"会从"登录"更改为"已登录"以反映登录状态.但是,如果我现在刷新页面,则基本按钮保留标题"已登录",而自定义按钮将其标题更改回"登录",建议(错误地)登录状态已通过页面更改刷新.

如果我通过运行以下命令在浏览器控制台中手动检查登录后的登录状态:

auth = gapi.auth2.getAuthInstance()
auth.isSignedIn.get()
Run Code Online (Sandbox Code Playgroud)

我得到true了一个返回,表明刷新确实没有改变登录状态,这与按钮标题的改变相反.

所以我的问题是:如何使自定义按钮的行为与基本按钮相同,以便其标题在刷新时不会改变?我喜欢的基本按钮的另一个(相关的,我假设的)行为是在每个页面加载时调用按钮的"onsuccess"回调(如果用户已登录),而自定义按钮不执行此操作.所以我也想在自定义按钮上更改此行为以匹配基本按钮的行为.任何建议将不胜感激!


我传递给渲染的参数如下所示:

function renderButton() {
    gapi.signin2.render('mybutton', {
    'scope': 'profile email',
    'width': 125,
    'height': 40,
    'longtitle': false,
    'theme': 'light',
    'onsuccess': onSuccess,
    'onfailure': onFailure
  });
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*łka 8

你能提供你传递给按钮的参数吗?您能否确认JS控制台中没有任何错误,并且没有任何400/403/404/4xx请求?

我已经使用以下代码测试了此功能,它似乎工作得非常好(您必须将YOUR_CLIENT_ID替换为您的实际client_id).

<head>
   <meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
  <script>
    function onSuccess(googleUser) {
       console.log('onSuccess!');
    }

    function onCustomSuccess(googleUser) {
       console.log('onCustomSignIn!');
    }

    function signOut() {
      var auth2 = gapi.auth2.getAuthInstance();
      auth2.signOut().then(function () {
        console.log('User signed out.');
      });
    }

    function onLoad() {
      gapi.signin2.render('custom_signin_button', {
        'onsuccess': onCustomSuccess
      });
    }
  </script>

  <div class="g-signin2" data-onsuccess="onSuccess"></div>
  <div id="custom_signin_button"></div>
  <a href="#" onclick="signOut();">Sign out</a>

  <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

编辑:将基本范围声明为head的元标记是最佳解决方案.

<meta name="google-signin-scope" content="profile email">
Run Code Online (Sandbox Code Playgroud)