首页 > 解决方案 > Gmail API 的多用户同时身份验证

问题描述

我想在一个页面上显示我的多个帐户中的电子邮件总数。目前我对所有电子邮件帐户一一进行身份验证,然后将电子邮件计数存储在数组中。

但是,我需要在 10 秒后刷新计数,而且我不能每 10 秒进行一次身份验证。那么有什么方法可以让我保持多个 Gmail 帐户登录并定期获取电子邮件计数。

此方法获取电子邮件计数

function listLabels() {
  gapi.client.gmail.users.labels.get({
    'userId': 'me',
    'id': 'INBOX'
  }).then(function(response) {
    ct.push(response.result.messagesTotal)
  });
}

这用于身份验证:

var ct = [];
// Client ID and API key from the Developer Console
var CLIENT_ID = '<CLIENT ID>';

// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';

var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');

/**
 *  On load, called to load the auth2 library and API client library.
 */
function handleClientLoad() {
  gapi.load('client:auth2', initClient);
}

/**
 *  Initializes the API client library and sets up sign-in state
 *  listeners.
 */
function initClient() {
  gapi.client.init({
    discoveryDocs: DISCOVERY_DOCS,
    clientId: CLIENT_ID,
    scope: SCOPES
  }).then(function() {
    // Listen for sign-in state changes.
    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

    // Handle the initial sign-in state.
    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    authorizeButton.onclick = handleAuthClick;
    signoutButton.onclick = handleSignoutClick;
  });
}

/**
 *  Called when the signed in status changes, to update the UI
 *  appropriately. After a sign-in, the API is called.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    authorizeButton.style.display = 'none';
    signoutButton.style.display = 'block';
    listLabels();
  } else {
    authorizeButton.style.display = 'block';
    signoutButton.style.display = 'none';
  }
}

/**
 *  Sign in the user upon button click.
 */
function handleAuthClick(event) {
  gapi.auth2.getAuthInstance().signIn();
}

/**
 *  Sign out the user upon button click.
 */
function handleSignoutClick(event) {
  gapi.auth2.getAuthInstance().signOut();
}

标签: javascriptgoogle-oauthgmail-apigoogle-api-js-client

解决方案


推荐阅读