Google Analytics Tracking with Google Apps Script

You can use the Google Analytics API with Google App Script to track email opens, measure traffic to your HTML web app or even track your documents, forms and spreadsheets in Google Drive. If you have an add-on, you can use Google Analytics to track how people are using the add-ons through events in Analytics.

function google_analytics(url) {
  var data = [];

  data.push(
    ['v', '1'],
    ['tid', 'UA-xxxxxxxx-xx'],
    ['cid', uuid()],
    ['z', Math.floor(Math.random() * 10e7)],
    ['t', 'pageview'],
    ['dp', url],
    ['dt', url]
  );

  var payload = data
    .map(function (el) {
      return el.join('=');
    })
    .join('&');

  var options = {
    method: 'post',
    payload: payload,
  };

  UrlFetchApp.fetch('https://ssl.google-analytics.com/collect', options);
}

/* Generate a random UUID to anonymously identify the client */
function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

The Google Scripts calls the Google Analytics API over SSL and adds a page view (dp is Document path and dt is the Document title and both are set to the URL or event name).

This can artificially inflate your page views in analytics so the other option is to use Events - use ec (event category) and ea (event action) in place of dp and dt and set t (hit type) as event. The tracking print requests tutorial uses events.

Similarly, if you have an add-on and need to track sidebar opens or menu item clicks, the google_analytics(action_name) call will record all user activity in your Google Analytics.

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻