如何使用新的 google identity JS 库来处理工作表?

How do I use new google identity JS library to work with sheets?

Google 很久以前就引入了新的 Sign In JS 库(gsi),但是 Google Sheets 文档仍然显示使用 gapi 的示例。使用 gsi 实现 combine/replace gapi 的最佳方法是什么?我可以举个例子吗?

2022/02/04 更新:

关于 Google Identity Services JavaScript SDK 的文档刚刚可用。

对比Sign In With Google, which only handles authentication (see Authentication and authorization), this library handles OAuth tokens (see Using the token model)访问Google APIs,因此可以完全替代gapi.

请注意,尽管 GIS 无法调用 API,因此 Google 建议继续使用 gapi.clientref ):

You can safely continue using the gapi.client module from the Google API Client Library for JavaScript, and take advantage of its automatic creation of callable JS methods from a discovery document, batching multiple API calls, and CORS management functionality.

因此,在通过 GIS 获取访问令牌后,您可以使用 gapi 调用 API,或者在没有任何这些库的情况下调用 API (在下面的示例和官方文档中,XMLHttpRequest 用于此)。

示例 1:使用 Google 身份服务:

<html>
  <head>
    <script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
  </head>
  <body>
    <script>
      var client;
      var access_token;

      function initClient() {
        client = google.accounts.oauth2.initTokenClient({
          client_id: 'CLIENT_ID',
          scope: 'https://www.googleapis.com/auth/spreadsheets.readonly',
          callback: (tokenResponse) => {
            access_token = tokenResponse.access_token;
          },
        });
      }
      function getToken() {
        client.requestAccessToken();
      }
      function revokeToken() {
        google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
      }
      function listMajors() {
        var spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
        var range = 'Class Data!A2:E';
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
          }
        };
        xhr.open('GET', `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}`);
        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
        xhr.send();
      }
    </script>
    <h1>Google Identity Services Authorization Token model</h1>
    <button onclick="getToken();">Get access token</button> <br><br>
    <button onclick="listMajors();">Call Sheets API</button> <br><br>
    <button onclick="revokeToken();">Revoke token</button>
  </body>
</html>

示例 2. 将 GIS 与 GAPI:

结合使用
<html>
<head>
  <script src="https://accounts.google.com/gsi/client" onload="gisInit()" async defer></script>
  <script src="https://apis.google.com/js/api.js" onload="gapiLoad()" async defer></script>
</head>
<body>
  <script>

    var tokenClient;
    var access_token;

    function gapiStart() {
        gapi.client.init({
      }).then(function() {
        gapi.client.load('sheets', 'v4');
      }).then(function(response) {
        console.log('discovery document loaded');
      }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
      });
    }

    function gapiLoad() {
      gapi.load('client', gapiStart)
    }

    function gisInit() {
      tokenClient = google.accounts.oauth2.initTokenClient({
        client_id: 'CLIENT_ID',
        scope: 'https://www.googleapis.com/auth/spreadsheets.readonly',
        callback: (tokenResponse) => {
          access_token = tokenResponse.access_token;
        },
      });
    }

    function getToken() {
      tokenClient.requestAccessToken();
    }

    function listMajors() {
      gapi.client.sheets.spreadsheets.values.get({
        spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
        range: 'Class Data!A2:E',
      }).then(function(response) {
        var range = response.result;
        console.log(range);
      });
    }


    function revokeToken() {
      google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
    }

  </script>

  <h1>Google Identity Services Authorization and GAPI</h1>
  <button onclick="getToken();">Get access token</button> <br><br>
  <button onclick="listMajors();">Call Sheets API</button> <br><br>
  <button onclick="revokeToken();">Revoke token</button>
</body>
</html>

注:

这两个示例均基于官方文档中的示例,其中调用了 Calendar API(参见 Implicit flow examples)。

参考:

作为 Iamblichus 答案的补充,您可以保存 access_token 并将其与 setToken 方法一起使用。

<html>
<head>
  <script src="https://accounts.google.com/gsi/client" onload="gisInit()" async defer></script>
  <script src="https://apis.google.com/js/api.js" onload="gapiLoad()" async defer></script>
</head>
<body>
  <script>

    var tokenClient;
    var access_token;

    function gapiStart() {
        gapi.client.init({
      }).then(function() {
        **if (access_token)**
            **gapi.auth.setToken({access_token: access_token})**
        gapi.client.load('sheets', 'v4');
      }).then(function(response) {
        console.log('discovery document loaded');
      }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
      });
    }

    function gapiLoad() {
      gapi.load('client', gapiStart)
    }

    function gisInit() {
      tokenClient = google.accounts.oauth2.initTokenClient({
        client_id: 'CLIENT_ID',
        scope: 'https://www.googleapis.com/auth/spreadsheets.readonly',
        callback: (tokenResponse) => {
          access_token = tokenResponse.access_token;
          **window.localStorage.setItem("gtoken", tokenResponse.access_token);**
        },
      });
    }

    function getToken() {
      tokenClient.requestAccessToken();
    }

    function listMajors() {
      gapi.client.sheets.spreadsheets.values.get({
        spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
        range: 'Class Data!A2:E',
      }).then(function(response) {
        var range = response.result;
        console.log(range);
      });
    }


    function revokeToken() {
      google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
    }
    **if (window.localStorage.getItem("gtoken"))**
        **access_token = window.localStorage.getItem("gtoken")**

  </script>

  <h1>Google Identity Services Authorization and GAPI</h1>
  <button onclick="getToken();">Get access token</button> <br><br>
  <button onclick="listMajors();">Call Sheets API</button> <br><br>
  <button onclick="revokeToken();">Revoke token</button>
</body>
</html>