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 = [];

    ['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('=');

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

  UrlFetchApp.fetch('', 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

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory


Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

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

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

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

We will never send any spam emails. Promise.