監控使用者和工作階段狀態

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