Categories
Code

Gmail Tracking with Google Analytics and Apps Script

This Google Script inserts the Google Analytics code in your outgoing email messages to help you track delivery and opens. When the email is opened, the tracking image (__utm.gif) – a 1×1 pixels transparent GIF file – is downloaded on the visitor’s computer and the visit gets logged as an event in Google Analytics.

You can use this technique to track email newsletters and other platforms where the standard JavaScript based Analytics code cannot be added.

Google Analytics tracking URL supports several parameters but this Apps Script function only uses only the essential ones that are required for logging an event (utmt is set as event and not page which is the default) into Google Analytics.

Also see: Tracking Email Clicks with Analytics


/* Written by Amit Agarwal */

function getTrackingGIF(account, email, subject) {

  var imgURL = "https://ssl.google-analytics.com/collect?"
    + "v=1&t=event"
    + "&tid=" + account
    + "&z="   + Math.round((new Date()).getTime()/1000).toString()
    + "&cid=" + Utilities.getUuid()
    + "&ec=" + encodeURIComponent("Email Open")
    + "&ea=" + encodeURIComponent(subject.replace(/'/g, ""))
    + "&el=" + encodeURIComponent(email);

  return "";

}

function sendMail(draftId, analyticsID) {

  var draft = GmailApp.getMessageById(draftId);
  
  var body = draft.getBody();
  body += getTrackingGIF(analyticsID, draft.getTo(), draft.getSubject());  
  
  GmailApp.sendEmail(draft.getTo(), draft.getSubject(), email, {
    htmlBody: email, cc: draft.getCc(), bcc: draft.getBcc()
  });          
}

Categories
Code

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.

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:

Click here

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.

Categories
Code

Use Google Analytics without JavaScript

The tutorial — tracking Gmail opens with Google Analytics – — uses Google Script to insert the Google Analytics tracking code into the outgoing email messages without requiring JavaScript.

The script creates a 1×1 tracking GIF that creates an event in your Google Analytics when a recipient opens your email. Since Gmail now automatically downloads images, the email open activity is very likely to be tracked.

Apps Script can track email opens using both Classic Google Analytics (utm) and the new Universal Analytics and requires no JavaScript.

/* 
  Email Tracking with Google Analytics
  ====================================
  Credit: http://labnol.org/?p=8082
*/

function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};

function guid() {
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

function emailTrackingGIF(version, email_address, email_subject, event_name) {

    /* Google Analytics Account ID like UA-1234-56 */
    var account = "UA-12345-XX";

    /* Random ID to prevent browser caching */
    var z = (Math.round((new Date()).getTime() / 1000)).toString();

    var imageURL = "";
    
    if (version == "universal") {
        
        imageURL = "https://ssl.google-analytics.com/collect?v=1&t=event"
                 + "&ec=" + encodeURIComponent(event_name)
                 + "&tid=" + account 
                 + "&z=" + z 
                 + "&cid=" + guid() 
                 + "&ea=" + encodeURIComponent(email_subject.replace(/'/g, "")) 
                 + "&el=" + email_address;

    } else if (version == "classic") {

        /* Relative path of the Web Page to be tracked */
        var utmp = "/inbox/" + email_address.replace("@", ".");

        var utme = encodeURIComponent("5(" + event_name + "*" + email_address + "*" + email_subject + ")");

        var request = "http://www.google-analytics.com/__utm.gif?" 
                    + "utmac=" + account 
                    + "&utmn=" + z 
                    + "&utmp=" + utmp 
                    + "&utmdt=" + encodeURIComponent(email_subject) 
                    + "&utme=" + utme 
                    + "&utmr=0&utmwv=5.4.5&utmhn=labnol.org&utmt=event&utmcc=__utma%3D999.999.999.999.999.1%3B";
    }
}
Categories
Code

Google Analytics PHP Tracking Code

This PHP script creates a 1×1 invisible image (__utm.gif) for tracking print usage using Google Analytics.

The Google Analytics Profile ID and the Landing Page URL are passed to the script via GET Parameters while the Referrer and User Agent string are determined from the request headers.

 array(
          "method" => "GET",
          "user_agent" => $_SERVER["HTTP_USER_AGENT"],
          "header" => ("Accept-Language: " . 
                          $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    );
    if (!empty($_GET["utmdebug"])) {
      $data = file_get_contents(
          $utmUrl, false, stream_context_create($options));
    } else {
      $data = @file_get_contents(
          $utmUrl, false, stream_context_create($options));
    }
  }

  // Track a page view, updates all the cookies and campaign tracker,
  // makes a server side request to Google Analytics and writes the 
  // transparent gif byte data to the response.
  function trackPageView() {
    $timeStamp = time();
    $domainName = $_GET["d"];
    if (empty($domainName)) {
      $domainName = "";
    }

    // Get the referrer from the utmr parameter
    $documentReferer = $_GET["utmr"];
    if (empty($documentReferer) && $documentReferer !== "0") {
      $documentReferer = "-";
    } else {
      $documentReferer = urldecode($documentReferer);
    }

    $documentPath = '/print' . urldecode($_GET["u"]);

    $account = $_GET["id"];
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (empty($userAgent)) {
      $userAgent = "";
    }

    // Try and get visitor cookie from the request.
    $cookie = $_COOKIE[COOKIE_NAME];

    $guidHeader = $_SERVER["HTTP_X_DCMGUID"];
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_UP_SUBNO"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_JPHONE_UID"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_EM_UID"];
    }

    $visitorId = getVisitorId($guidHeader, $account, $userAgent, $cookie);

    // Always try and add the cookie to the response.
    setrawcookie(
        COOKIE_NAME,
        $visitorId,
        $timeStamp + COOKIE_USER_PERSISTENCE,
        COOKIE_PATH);

    $utmGifLocation = "http://www.google-analytics.com/__utm.gif";

    // Construct the gif hit url.
    $utmUrl = $utmGifLocation . "?" .
        "utmwv=" . VERSION .
        "&utmn=" . getRandomNumber() .
        "&utmhn=" . urlencode($domainName) .
        "&utmr=" . urlencode($documentReferer) .
        "&utmp=" . urlencode($documentPath) .
        "&utmac=" . $account .
        "&utmcc=__utma%3D999.999.999.999.999.1%3B" .
        "&utmvid=" . $visitorId .
        "&utmip=" . getIP($_SERVER["REMOTE_ADDR"]);

    sendRequestToGoogleAnalytics($utmUrl);

    writeGifData();
  }
?>