Google+使用JavaScript登录-立即调用两次回调

Google+ Sign in with JavaScript – callback called twice immediately

本文关键字:回调 两次 调用 JavaScript 使用 登录 Google+      更新时间:2023-09-26

我正在尝试按照Google+的指导,使用我自己的按钮启动Google+登录流。

关于回调函数,gap.auth.signIn引用说(quote):

全局命名空间中的一个函数,它在呈现登录按钮时被调用,也在登录流完成后被调用。

出现Google登录对话框,要求我登录,但在与对话框进行任何交互之前,回调会立即调用两次。这两次我都得到了类似的authResult,错误="immediate_failed",错误_子类型="access_denied",状态.signed_in=false

为什么?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8" />
    <script src="https://apis.google.com/js/client:platform.js?onload=googleRender" async defer></script>
  </head>
  <body>
<script>
  function googleRender() {  // executed when Google APIs finish loading
    var googleSigninParams = {
      'clientid' : '746836915266-a016a0hu45sfiouq7mqu5ps2fqsc20l4.apps.googleusercontent.com',
      'cookiepolicy' : 'http://civoke.com',
      'callback' : googleSigninCallback ,
      'requestvisibleactions' : 'http://schema.org/AddAction',
      'scope' : 'https://www.googleapis.com/auth/plus.login'
    };
    var googleSigninButton = document.getElementById('googleSigninButton');
    googleSigninButton.addEventListener('click', function() {
      gapi.auth.signIn(googleSigninParams);
    });
  }
  function googleSigninCallback(authResult) {
    console.log('googleSigninCallback called: ');
    console.dir(authResult);
    if (authResult['status']['signed_in']) {
      document.getElementById('googleSigninButton').setAttribute('style', 'display: none');  // hide button
      console.log('User is signed-in to Google');
    } else {
      console.log('User is NOT signed-in. Sign-in state: ' + authResult['error']);
    }
  }
</script>
<button id="googleSigninButton">Sign in with Google</button>
  </body>
</html>

回调函数总是在状态发生变化时调用,而不仅仅是在用户登录时调用。在googleSigninCallback(authResult)中,您应该首先检查用户是否已登录,然后检查方法值是AUTO还是PROMPT。当用户登录时,PROMPT应该只返回一次,这正是您所需要的。这是代码:

function googleSigninCallback(authResult) {
  if (authResult['status']['signed_in'] && authResult['status']['method'] == 'PROMPT') {
      // User clicked on the sign in button. Do your staff here.
  } else if (authResult['status']['signed_in']) {
      // This is called when the status has changed and method is not 'PROMPT'.
  } else {
      // Update the app to reflect a signed out user
      // Possible error values:
      //   "user_signed_out" - User is signed-out
      //   "access_denied" - User denied access to your app
      //   "immediate_failed" - Could not automatically log in the user
      console.log('Sign-in state: ' + authResult['error']);
  }