Drive Activity API v1 has reached the end of its deprecation period and is shutting down as announced in December 2018. Migrate to API v2 as soon as possible to avoid disruptions to your application.

JavaScript Quickstart

Complete the steps described in the rest of this page to create a simple JavaScript web application that makes requests to the Google Drive Activity API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Python 2.4 or greater (to provide a web server)
  • A Google Cloud Platform project with the API enabled. To create a project and enable an API, refer to Create a project and enable the API
  • Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.
  • A Google account

Step 1: Set up the sample

To set up the sample:

  1. In your working directory, create a file named index.html.
  2. Include the following code in index.html:

    drive/activity-v2/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Drive Activity API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Drive Activity API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
        <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): Set to client ID and API key from the Developer Console
          const CLIENT_ID = '<YOUR_CLIENT_ID>';
          const API_KEY = '<YOUR_API_KEY>';
    
          // Discovery doc URL for APIs used by the quickstart
          const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/driveactivity/v2/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/drive.activity.readonly';
    
          let tokenClient;
          let gapiInited = false;
          let gisInited = false;
    
          document.getElementById('authorize_button').style.visibility = 'hidden';
          document.getElementById('signout_button').style.visibility = 'hidden';
    
          /**
           * Callback after api.js is loaded.
           */
          function gapiLoaded() {
            gapi.load('client', intializeGapiClient);
          }
    
          /**
           * Callback after the API client is loaded. Loads the
           * discovery doc to initialize the API.
           */
          async function intializeGapiClient() {
            await gapi.client.init({
              apiKey: API_KEY,
              discoveryDocs: [DISCOVERY_DOC],
            });
            gapiInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Callback after Google Identity Services are loaded.
           */
          function gisLoaded() {
            tokenClient = google.accounts.oauth2.initTokenClient({
              client_id: CLIENT_ID,
              scope: SCOPES,
              callback: '', // defined later
            });
            gisInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Enables user interaction after all libraries are loaded.
           */
          function maybeEnableButtons() {
            if (gapiInited && gisInited) {
              document.getElementById('authorize_button').style.visibility = 'visible';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick() {
            tokenClient.callback = async (resp) => {
              if (resp.error !== undefined) {
                throw (resp);
              }
              document.getElementById('signout_button').style.visibility = 'visible';
              document.getElementById('authorize_button').innerText = 'Refresh';
              await listActivities();
            };
    
            if (gapi.client.getToken() === null) {
              // Prompt the user to select a Google Account and ask for consent to share their data
              // when establishing a new session.
              tokenClient.requestAccessToken({prompt: 'consent'});
            } else {
              // Skip display of account chooser and consent dialog for an existing session.
              tokenClient.requestAccessToken({prompt: ''});
            }
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick() {
            const token = gapi.client.getToken();
            if (token !== null) {
              google.accounts.oauth2.revoke(token.access_token);
              gapi.client.setToken('');
              document.getElementById('content').innerText = '';
              document.getElementById('authorize_button').innerText = 'Authorize';
              document.getElementById('signout_button').style.visibility = 'hidden';
            }
          }
    
          /**
           * Print recent activity.
           */
          async function listActivities() {
            let response;
            try {
              response = await gapi.client.driveactivity.activity.query({
                'pageSize': 10,
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
    
            const activities = response.result.activities;
            if (!activities || activities.length == 0) {
              document.getElementById('content').innerText = 'No activities found.';
              return;
            }
            // Flatten to string to display
            const output = activities.reduce(
                (str, activity) => {
                  const time = getTimeInfo(activity);
                  const action = getActionInfo(activity['primaryActionDetail']);
                  const actors = activity.actors.map(getActorInfo);
                  const targets = activity.targets.map(getTargetInfo);
                  return `${str}${time}: ${truncated(actors)}, ${action}, ${truncated(targets)}\n`;
                },
                'Activities:\n');
            document.getElementById('content').innerText = output;
          }
    
          // Utility methods for formatting activity records
    
          /**
           * Returns a string representation of the first N elements in a list.
           * @param {string[]} array - Values to join
           * @param {number} limit - # of elements to show
           * @return {string} formatted string
           */
          function truncated(array, limit = 2) {
            const contents = array.slice(0, limit).join(', ');
            const more = array.length > limit ? ', ...' : '';
            return `[${contents}${more}]`;
          }
    
          /**
           * Returns the first found property name in an object.
           * @param {object} object - Object to search
           * @return {string} key name or 'unknown'
           */
          function getOneOf(object) {
            const props = Object.getOwnPropertyNames(object);
            if (props.length === 0) {
              return 'unknown';
            }
            return props[0];
          }
    
          /**
           * Returns a time associated with an activity.
           * @param {object} activity - Activity record
           * @return {string} Formatted timestamp
           */
          function getTimeInfo(activity) {
            if ('timestamp' in activity) {
              return activity.timestamp;
            }
            if ('timeRange' in activity) {
              return activity.timeRange.endTime;
            }
            return 'unknown';
          }
    
          /**
           * Returns the type of action.
           * @param {object} actionDetail
           * @return {string} Action type as string
           */
          function getActionInfo(actionDetail) {
            return getOneOf(actionDetail);
          }
    
          /**
           * Returns user information, or the type of user if not a known user.
           * @param {object} user - User record
           * @return {string} user type as string
           */
          function getUserInfo(user) {
            if ('knownUser' in user) {
              const knownUser = user['knownUser'];
              const isMe = knownUser['isCurrentUser'] || false;
              return isMe ? 'people/me' : knownUser['personName'];
            }
            return getOneOf(user);
          }
    
          /**
           * Returns actor information, or the type of actor if not a user.
           * @param {object} actor - Actor record
           * @return {string} actor type as string
           */
          function getActorInfo(actor) {
            if ('user' in actor) {
              return getUserInfo(actor['user']);
            }
            return getOneOf(actor);
          }
    
          /**
           * Returns the type of a target and an associated title.
           * @param {object} target - Activity target record
           * @return {string} target type as string
           */
          function getTargetInfo(target) {
            if ('driveItem' in target) {
              const title = target.driveItem.title || 'unknown';
              return `driveItem:"${title}"`;
            }
            if ('drive' in target) {
              const title = target.drive.title || 'unknown';
              return `drive:"${title}"`;
            }
            if ('fileComment' in target) {
              const parent = target.fileComment.parent || {};
              const title = parent.title || 'unknown';
              return `fileComment:"${title}"`;
            }
            return `${getOneOf(target)}:unknown`;
          }
        </script>
        <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
        <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
      </body>
    </html>

  3. In the code, replace <YOUR_CLIENT_ID> with the client ID you created as a Prerequisite for this quickstart.

  4. In the code, replace <YOUR_API_KEY> with the API key you created as a Prerequisite for this quickstart.

Step 2: Run the sample

To run the sample:

  1. Start the web server using the following command from your working directory:

Python 2.x

python -m SimpleHTTPServer 8000

Python 3.x

python -m http.server 8000
  1. In your browser, navigate to http://localhost:8000.

  2. (optional). If this is your first time running the sample, the sample opens an OAuth consent screen prompting you to authorize the app to access your data on your behalf:

    1. If you are not already signed in to your Google account, you are prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for authorization.

    2. Click Accept. The app is authorized to access your data.

  3. The sample executes.

If you have problems, refer to the Troubleshoot the sample section.

Troubleshoot the sample

This section describes some common issues that you can encounter while attempting to run this quickstart.

Error: origin_mismatch

This error occurs during the authorization flow if the host and port used to serve the web page doesn't match an allowed JavaScript origin on your Google Developers Console project. Make sure you set an authorized JavaScript origin and that the URL in your browser matches the origin's URL.

idpiframe_initialization_failed: Failed to read the 'localStorage' property from 'Window'

This error occurs when 3rd party cookies and data storage aren't enabled in your browser. These options are required by the Google Sign-in library. For further information, refer to 3rd party cookies and data storage.

idpiframe_initialization_failed: Not a valid origin for the client

This error occurs when the domain registered as a Prerequisite doesn't match the domain being used to host the web page. Ensure that the origin you registered as a Prerequisite matches the URL in the browser.

This app isn't verified

If the OAuth consent screen displays the warning "This app isn't verified," your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your app must go through the verification process to remove that warning and other limitations. During the development phase, you can continue past this warning by selecting Advanced > Go to {Project Name} (unsafe).

Further reading

For further information on the APIs used in this quickstart, refer to the Google API Client Library for JavaScript section of GitHub.