同时针对Gmail API进行多用户身份验证

时间:2018-07-18 07:43:18

标签: javascript google-oauth gmail-api google-api-js-client

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

但是,我需要在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();
}

0 个答案:

没有答案