监控用户的会话状态

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