User Intention Tracking in Google Analytics: The Javascript

The Goal

Our marketing team wanted better insight into exactly how PPC traffic was behaving for a catering client. Information is set when a user clicks a Google AdWords advertisement, or similar ads on MSN and Yahoo!. Normally, when a user arrives at a Google Analytics tracked site, this information is placed in a cookie. This cookie expires at the completion of a user's session on the site (or for other reasons). We wished to retain the knowledge that a user had arrived at the site via advertising, at some point, in order to see if that user eventually signed up, or made a purchase, or some other goal.

The Execution

To accomplish this, we chose to use Google's "user defined variables". These are set using the 'setVar' method, in javascript.

First, we had to determine if an inbound user was, in fact, coming from an advertisement. For MSN and Yahoo! this was a simple matter of checking for 'cpc' as a part of the utmz cookie that GA defines. For AdWords we had to detect the existence of a 'gclid', the ID used by Google Analytics. Here's the javascript we include after a new pageTracker is made:

 document.cookie.split(';').each(function(cookie) { if(cookie.indexOf('__utmz') != '-1') utmz = cookie; }); if(utmz) { var cpc_regex = new RegExp(".*?utmcmd=([a-z]+)\|"); medium = utmz.match(cpc_regex)[1]; var gclid_regex = new RegExp(".*?utmgclid=([\_0-9A-Za-z]+)\|"); adwords = utmz.match(gclid_regex)[1]; if(medium == 'cpc' || adwords) pageTracker._setVar('CPC'); } 

This, very specifically, looks for the medium and gclid and always requires the existence of the cookies set by GA. It is the simplest thing that works for us. It could easily be adapted to check for other information (like referrer) and set a variable or do any number of other things with javascript.

If you have seen this done before, or have an alternative method, please leave a comment as we would love to hear about it.

To find out why we needed this information and how it is useful please read the companion post from Josh, on our Engage Blog.

Tony Pitale

,
Posted in Article Category: #Code
on