2014-10-19 74 views
7

我在嘗試按照Google+指南啓動Google+使用我自己的按鈕登錄流程。Google+使用JavaScript - 回叫立即呼叫兩次

關於回調函數,該gapi.auth.signIn參考說(報價):

「在全球命名空間的功能,當登錄按鈕被渲染,也被稱爲在登錄流程完成後調用。「

的谷歌登錄對話框出現後,要求我簽署的,但回調調用兩次立即,任何交互與對話才製成。兩次我得到一個類似的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> 

回答

7

回調函數中總是調用時的狀態發生了變化,不僅在用戶登錄時,在googleSigninCallback(authResult),你應該首先檢查一下您的使用者登入,然後你應該檢查,如果方法值AUTOPROMPTPROMPT應該只在用戶登錄時返回一次,這就是您需要的。這裏的代碼:

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']); 
    } 
+2

首先它的工作原理(謝謝)。兩個評論雖然:(1)當不是'PROMPT'我得到空而不是'自動'; (2)這仍然不能解釋爲什麼它被稱爲**兩次**因爲沒有兩個立即狀態更改... – 2014-10-27 07:07:59

+0

我一直在用這個撕掉我的頭髮。謝謝。 – Keab42 2015-06-12 13:21:24