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=""></script>
  onreadystatechange="if (this.readyState === 'complete') this.onload()"
  // Please set the service account.
  const object = {
    private_key: "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n",
    client_email: "###",
    scopes: [""],

  const handleClientLoad = () =>
    gapi.load("client", async () =>

  function run() {
        discoveryDocs: [
      .then(() => {
            pageSize: 10,
            fields: "files(name)",
          .then(({ body }) => {
  • 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.


Cheking script

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