Cross Domain Google Analytics – Easier with jQuery

We run two public facing websites at the company I work for, sitting on different domains. Recently our marketing team requested that we enable cross-domain tracking under Google Analytics to allow them to track a user’s journey between the two sites, rather than losing them at the boundary.

Google has extensive documentation on enabling cross domain analytics but the long and the short of it is that at links which cross the boundary, you need a wee bit of javascript to push an analytics event, something like this:

<a href="http://www.my-other-domain.com/intro"
   onclick="_gaq.push(['_link', 'http://www.my-other-domain.com/intro.html']); return false;">
   Some Link</a>

For two domains with a bunch of joining links, this adds a tedious task of chaning links, and an ongoing overhead in terms of ensuring that news links added to the site which cross the domain boundary include the relevant onClick event. Surely we can do better? Enter jQuery.

Adding the following snippet to your Site.Master, Razor Layout or equivalent will automatically add the relevant click events to all links containing the relevant domain. Simple!

$('a[href*="my-other-domain.com"]').each(function (index, link) {
    $(link).click(function () {
        _gaq.push(['_link', $(link).attr('href')]);
        return false;
    });
 });
Advertisements
This entry was posted in Code and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s