Google Analytics Tracking with Google Apps Script

Published in: Google Analytics - 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 = {
                           return el.join('=')}).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.

Published in: Google Analytics - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
Amit Agarwal

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. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch