Adjusting Cross-Domain Analytics Data

Anyone that’s used Google Analytics to track cross-domain requests has probably run up against the fact that Analytics adds some really ugly GET variables to the end of your URLs when you click on links. Not only are they ugly, but they also can stop things like WP Super Cache from caching your pages. We also found that the query string appended by Google Analytics was causing server errors when appended to the URLs of some of our hosted apps.

There is a little-publicized feature in Analytics, though, that lets you change the query string into a hash string. Therefore, instead of having some long, ugly string that can mess things up (and, to be honest, long, confusing query strings can sometimes scare users); you get a long, ugly hash appended to the URL, instead (which has no effect on the way the page is rendered, and, therefore, doesn’t mess up nearly as many things).

To change the query string to a hash, you’ll first need to set up cross-domain tracking.

Next, you need to add a single line of JavaScript to tell Analytics that you might be using the hash instead of the query string. For the newest version (async) of the Analytics tracking code, that line looks basically like:

_gaq.push(['pageTracker._setAllowAnchor',true]);

I’m not 100% certain that parameter is required anymore (I couldn’t find much documentation on that particular property as it relates to the async version of Analytics).

Then, you’ll need to add some JavaScript that adds the appropriate tracking information to external links. That might look something like:

	jQuery('a').filter( function() { 
		return this.hostname != location.hostname && !this.href.match(/^mailto\:/);
	} ).click( function() { 
		_gaq.push(['_link', jQuery(this).attr('href'), true]); 
		return false; 
	} );

Notice, in the _gaq.push() call, near the bottom of that code, the array being pushed has 3 members. Most of the cross-domain tracking tutorials you’ll find will only send 2 members (the ‘_link’ name and the URL you want to track). The third item is a boolean value that tells Analytics whether to append the information as a hash (true) or a query string (false – default).

That’s all there is to it.