监控用户的会话状态

初始化 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);
};