Using Google API Client Library (gapi) for JavaScript with Service Account

Gists

This is a sample script for using Google API Client Library (gapi) for JavaScript with the service account. Unfortunately, in the current stage, gapi cannot directly use the service account. So, in this case, it is required to implement the script for retrieving the access token from the service account. In this report, I would like to introduce the method for using gapi with the service account using a Javascript library.

Sample script

In this sample script, GetAccessTokenFromServiceAccount_js of Javascript library is used. Before you use this script, please set your private_key, client_email and scopes to the variable of object.

<input type="button" value="Run" onClick="run()" />

<script src="https://cdn.jsdelivr.net/gh/tanaikech/GetAccessTokenFromServiceAccount_js@master/getaccesstokengromserviceaccount_js.min.js"></script>
<script
  async
  defer
  src="https://apis.google.com/js/api.js"
  onload="this.onload=function(){};handleClientLoad()"
  onreadystatechange="if (this.readyState === 'complete') this.onload()"
></script>
<script>
  // Please set the service account.
  const object = {
    private_key: "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n",
    client_email: "###",
    scopes: ["https://www.googleapis.com/auth/drive.readonly"],
  };

  const handleClientLoad = () =>
    gapi.load("client", async () =>
      gapi.auth.setToken(await GetAccessTokenFromServiceAccount.do(object))
    );

  function run() {
    gapi.client
      .init({
        discoveryDocs: [
          "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest",
        ],
      })
      .then(() => {
        gapi.client.drive.files
          .list({
            pageSize: 10,
            fields: "files(name)",
          })
          .then(({ body }) => {
            console.log(body);
          });
      });
  }
</script>
  • When you run above script, the file list of the Google Drive of service account is obtained.

  • gapi.client.load method has already been deprecated. Please be careful this. Ref By this, gapi.client.init is used. Ref

  • For example, when an error like Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null'). occurred, please try to run the HTML on the server instead of the local PC.

References

Cheking script

  • November 28, 2022: It confirmed that this sample script worked.

 Share!