Howto - using JS to set Campaign Values in Google Analytics

Posted 12 years ago by Internetrix

7 Minute(s) to read

If you want to capture campaign traffic, however, and you can't ensure incoming blog links put all the tricky campaign codes in the address for make life easier for you, or you want to do any form of offline marketing with a web "call to action", you haven't really had a choice. Until now.

Setting Campaigns using JavaScript

At Internetrix, we've been implementing an approach with the Google Analytics module in our Freestyle Content Management System that allows users to set their campaign codes, dynamically, and according to one or more rules, using JavaScript. No more ugly URLs. No more trying to figure out how to account for your campaigns by adding together campaign, referral site and a bunch of other reports in the GA reporting interface. Just simple, easy to set - and suspend - campaign tagging within your website.

While the module provides the ability to set campaign values based on over a dozen different data points, and to set campaigns for very specific periods of time, the basics of how we've been able to manipulate the Google Analytics Tracking Code (GATC) are something we thought we'd share - the community, particularly Google Analytics Authorized Consultants have certainly given us a lot of great information and ideas about how to help our clients get the most out of Google Analytics.

Now, we're going to get a bit technical here. If you get stuck, please check out our Google Analytics services page, or get in touch by requesting a quote, and we'd only be too happy to help you out. With that out of the way, lets get coding!

Know your GATC version

Firstly, know what version of the Google Analytics Tracking Code (GATC) you're using. There are two versions in circulation - the urchin.js version which is older and a bit easier to work with, and the ga.js version, which is newer, more object orientated, but heavily obfuscated. Don't worry - we'll cover how to use either of them here, but make sure you know what you're working with first.

urchin.js dynamic campaign tracking

Tracking campaigns is all about tricking Google Analytics into thinking your address bar contains the extra text that we've shown in the example above.

If you've got some knowledge of JavaScript, you'll know you can read out the values in the address bar from the document.location object in the Document Object Model. You'd probably also know that you can't go and set the value as document.location via JavaScript without your web browser seeing that as an invitation to go to a new address, immediately teleporting you, just like we don't want to!

The secret is to make a "deep copy" of the _udl variable, which urchin.js sets up automatically, and then to modify the value of this copy before reinserting the now-modified copy into the original _udl variable, just before you call "urchinTracker()".

Some sample code for this is contained below:

<script type="text/javascript" language="Javascript">

_uacct = 'UA-123456789-1';

var campaign_source ='web';
var campaign_title ='Freestyle June 08';
var campaign_medium ='cpc';
var campaign_content ='Blog Traffic';

var loc = new Object();

for (var key in _udl) = "?utm_source="+campaign_source+"&utm_campaign="+campaign_title +"&utm_medium="+campaign_medium+"&utm_content="+campaign_content;

_udl = loc;


Talking you through it:

  • The first section is the standard loading process for urchin.js and setting up your GA account number.
  • The next four lines are where we set the variables for our code. These values can contain pretty much anything you want - beware of = signs and & characters.
  • The two lined are where we do the magic. We get the values contained in the _udl object - which is itself a shallow copy of document.location, and which is used inside urchin.js - and deep copy them over to a new object which we can mess with without causing the page to reload and teleport.
  • With the values in our loc object, we can set to contain the new query string parameters; this mimics what a link tag would contain.
  • Finally, we set this value back into _udl, which is then used in the next line where urchinTracker() gets called, when the __utmz cookie value is set to contain the campaign data you've just created.

As you'll see from the above code, we're setting the values for the campaign completely via JavaScript. With this knowledge, you can now put IF statements around the process of setting the variables; this way, anything variable you can access from JavaScript, you can use to tailor what gets set, and when.

This is a very high level of look at things, and there's a lot more to it than this; for more information on making this happen, experiment yourself with something like Firefox and LiveHTTP headers, or contact us for professional consulting if it all gets a bit much.

ga.js dynamic campaign tracking

If you thought messing with urchin.js above was tricky, you ain't seen nothing yet. ga.js is the new object oriented version, and we're guessing Google built it with its vaunted Google Web Toolkit, which makes JavaScript almost unreadable. Thankfully, we've got some team members with rain-man like powers, and we've cracked the code if you will to enable you to do client side JavaScript setting of campaign values.

Without any further ado, here's the code we use:

var pageTracker = _gat._getTracker("UA-123456789-1");


var z = pageTracker.u.V[4][1]().split('.');

var cookies = pageTracker.a.cookie.split(';');

if (!z[2] || !z[3])
// if we don't have the nsessions or nresponse, get them directly from the cookies

for (i=0;i<cookies.length;i++)>
{ .length;i++)>

var re = new RegExp(/__utmz\=(.*)/);
var mymatch = re.exec(cookies[i]);
if (mymatch)
z = cookies[i].split('.');



if (z[2] && z[3])
// if anything has changed, override

var campaign_source ='web';
var campaign_title ='Freestyle June 08';
var campaign_medium ='cpc';
var campaign_content ='Blog Traffic';

var zstr_id = [pageTracker.f, pageTracker.ja, z[2],z[3]].join('.');

var zcsr ='utmcsr='+campaign_source;
var zccn = 'utmccn='+campaign_title;
var zcmd = 'utmcmd='+campaign_medium;
var zcct = 'utmcct='+campaign_content;

var zstr_content = [zcsr, zccn, zcmd, zcct].join('|');


This code is quite complicated and difficult to explain.

Essentially, we're using a number of anonymous functions, defined by array values within an object inside the pageTracker object, to set the internal copies of the values already slurped in by GA during the _initData() call.

WARNING: while urchin.js has been fairly stable, and remains fairly easy to read and notice changed in, ga.js is heavily compiled and obfuscated JavaScript. Combining this with the fact this version if a lot newer, and Google are releasing new features from time to time, there is a chance that this code will change, and when it does, a different anonymous function will need to be called to set these values.


In summary, setting campaign values via JavaScript opens up a whole new world of possibilities with Google Analytics. Aside from the use cases covered above, one of the more subtle but valuable benefits of this approach is that the standard Google Analytics reports are much easier to just use. Less filtering, less custom profiles, less trying to get rid of the irrelevant traffic in your campaigns after the fact, and a whole lot more useful campaign information straight out of Google Analytic's standard reports.

To find out more about how this approach could help in managing your online campaigns, check out Freestyle, our content management system, especially its Google Analytics campaign management module, which makes all of this code above as simple as point and click. If you're already quite happy with your CMS, but want to make some of this magic happen on your site, check out our Google Analytics services and request a quote today.