2015-06-18 68 views
0

我試圖在我的網站上建立Google登錄按鈕。我試圖避免使用他們的內置按鈕。下面的代碼用於登錄用戶,但我無法弄清楚如何讓我的網頁記住他們在用戶刷新頁面或離開網站並返回時登錄。Google SignIn狀態

使用Chrome的開發人員工具,我可以看到Local StorageSession Storage下都有https://accounts.google.com的條目。他們似乎或多或少地包含相同的信息,包括用戶的驗證令牌。

我不明白的是如何讓gapi.auth2.init()函數識別和使用這個令牌。 documentation似乎沒有涵蓋它。

<html> 
    <head> 
     <title>Login Test</title> 
     <script src="http://code.jquery.com/jquery-2.1.4.js"></script> 
     <script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script> 
    </head> 

    <script> 
     var googleUser = {}; 
     function renderButton() { 
      gapi.load('auth2', function(){ 
       auth2 = gapi.auth2.init({ 
        client_id: 'MY_CREDENTIALS.apps.googleusercontent.com', 
       }); 
       attachSignin(document.getElementById('customBtn')); 
      }); 
     }; 

     function attachSignin(element) { 
      auth2.attachClickHandler(element, {}, 
       function(googleUser) { 
        document.getElementById('name').innerText = "Signed in: " + 
         googleUser.getBasicProfile().getName(); 
       }, function(error) { 
        alert(JSON.stringify(error, undefined, 2)); 
       } 
      ); 
     } 
    </script> 

    <body> 
     <div id="gSignInWrapper"> 
      <span class="label">Sign in with:</span> 
      <input type="button" id="customBtn" value="Google"></input> 
     </div> 
     <p id="name"></p> 
    </body> 
</html> 

回答

4

您可以使用listeners。這是有關部分:

// Listen for sign-in state changes. 
auth2.isSignedIn.listen(signinChanged); 

// Listen for changes to current user. 
auth2.currentUser.listen(userChanged); 

還可以獲得最新的值由

var isSignedIn = auth2.isSignedIn.get(); 
var currentUser = auth2.currentUser.get(); 

要嚴格檢測返回用戶唯一可以做的:

var auth2 = gapi.auth2.init(CONFIG); 
auth2.then(function() { 
    // at this point initial authentication is done. 
    var currentUser = auth2.currentUser.get(); 
}); 

當談到您的代碼我會這樣做:

auth2 = gapi.auth2.init(CONFIG); 
auth2.currentUser.listen(onUserChange); 
auth2.attachClickHandler(element, {}); 

這樣,登錄狀態中的所有更改都會傳遞給onUserChange(這包括返回用戶,來自attachClickHandler的新登錄,來自不同選項卡的新登錄)。

+0

我插入了auth2.currnetUser.listen(onUserChange);並得到一個錯誤,指出onUserChange未定義。 – Jacobm001

+0

auth2.currentUser(你有currnet)。你必須自己實現onUserChange處理程序。在https://developers.google.com/identity/sign-in/web/上檢查onSignIn函數。 –

+0

謝謝,解決了我遇到的問題:) – Jacobm001