Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active December 23, 2022 07:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/603102a64587cb9bff2e165994f6b6a1 to your computer and use it in GitHub Desktop.
Save tanaikech/603102a64587cb9bff2e165994f6b6a1 to your computer and use it in GitHub Desktop.
Using Google API Client Library (gapi) for JavaScript with Service Account

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

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment