ユーザーのセッション状態のモニタリング

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);
};