初始化 Google 登入用戶端後,您可以附加處理常式來檢查用戶端的各種屬性和方法,藉此判斷使用者的工作階段狀態。您可以使用用戶端物件傳回的資訊,為使用者在多個分頁和裝置中同步處理網站使用者體驗。
以下程式碼示範如何使用 2.0 用戶端方法 attachClickHandler
建立回呼,在無訊息的情況下完成使用者的登入程序,或提示使用者根據使用者工作階段的狀態重新授權。
/**
* The Sign-In client object.
*/
var auth2;
/**
* Initializes the Sign-In client.
*/
var initClient = function() {
gapi.load('auth2', function(){
/**
* Retrieve the singleton for the GoogleAuth library and set up the
* client.
*/
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com'
});
// Attach the click handler to the sign-in button
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
});
};
/**
* Handle successful sign-ins.
*/
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
};
/**
* Handle sign-in failures.
*/
var onFailure = function(error) {
console.log(error);
};