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 = {
                           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.

To give you an example, if you are to track how often a link was clicked inside an add-on, you can modify the href tag like this:

<a href="" onclick="google_analytics('ctrlq clicked'); return;">Click here</a>

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.