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

时间:2014-10-19 12:52:05

标签: javascript google-plus google-login

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

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

  

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

出现Google登录对话框,要求我登录,但在与对话框进行任何交互之前,会立即调用两次立即回调。两次我得到一个类似的authResult,错误=" immediate_failed",error_subtype =" access_denied",status.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>

1 个答案:

答案 0 :(得分:8)

当状态发生变化时,总是会调用回调函数,而不仅仅是在用户登录时。在googleSigninCallback(authResult)中,您应该首先检查用户是否已登录,然后您应该检查,如果方法值是AUTOPROMPT。当用户登录时,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']);
  }
相关问题