Google Analytics Integration with jQuery

by Jason. 42 Comments

Google Analytics is now an essential part of every site we produce. Unless you’ve been living under a rock, you should know that Google purchased Urchin, an industry-leading web analytics package, a few years back, and made a web-based version of it available for free. (Thanks, Google!)In contrast to traditional web log analyzers, Google Analytics collects data via a JavaScript (urchin.js) you add to each page you wish to track. On each page load, a function in the JavaScript (urchinTracker) requests a GIF file from Google and appends a query string full of data onto the request.

When you sign up for a Google Analytics account, you’re provided with a javascript code snippet which includes a unique account number, and you’re instructed to include this snippet on every page in your site that you wish to track. At a glance, this appears to be “all there is to it”, but of course you can do much more.

The Analytics site provides a few recommendations for tracking certain user activity that a single call to urchinTracker doesn’t catch on its own. It’s far from a comprehensive guide, but at this point the capabilities of the script have been pretty thoroughly reverse engineered by end users.

For instance, your web site may include resources that are not standard web pages. Things like PDF files, MP3′s, ZIP archives, etc. Since there is no way to embed the tracking script directly within these resources, we must instead track when users click on links to those resources from within other pages. Similarly, you may also wish to track links to external sites and/or mailto links. If you own an e-commerce site, or want to take advantage of the “campaigns” feature of Google Analytics, the customization can get even deeper.

Identifying and marking up these types of links is simple in concept, but difficult in practice in a modern site where multiple users may be contributing content through a CMS with no knowledge of HTML or JavaScript. Clearly, some form of automation is required. I decided to write a jQuery plugin to make embedding Google Analytics simpler for typical web sites. Currently the plugin does the following:

  • Determine whether to include the SSL or non-SSL version of the GA script.
  • Include the GA script from within try/catch to help suppress any issues GA may have from time to time.
  • Set the _uacct variable to your GA tracking code.
  • Call the urchinTracker() function once for the initial page load.
  • Examine all of the links on the page and attach onclick events to:
    • External links.
    • Mailto links.
    • Downloads.
  • Call urchinTracker() when these links are clicked, prefixing them appropriately.

In addition to the tracking code, the prefixes used for each of the link types above, as well as the extensions considered “downloadable files” are configurable by the user.

It requires jQuery 1.2 or higher for the cross-domain $.getScript() call. Usage is simply:

$.gaTracker('UA-XXXXX-XX');

Or you can specify options like so:

$.gaTracker(
    'UA-XXXXX-XX',
    {
        external:       '/external/',
        mailto:         '/mailto/',
        download:       '/downloads/',
        extensions:     [
            'pdf','doc','xls','csv','jpg','gif', 'mp3',
            'swf','txt','ppt','zip','gz','dmg','xml'
        ]
    }
);

Download the gaTracker plugin at jQuery.com.

42 Responses to Google Analytics Integration with jQuery

  1. Alexandre says:

    It sounds great, but it would be great to have an example with the before and after. It looks like I can do exactly what I need, but I don’t really understand how to replace my existing basic google code with this…

  2. Jason says:

    @Alexandre – You completely remove the original code snippet provided by Google. So, instead of something like this:

    <script src=”http://www.google-analytics.com/urchin.js” type=”text/javascript”>
    </script>
    <script type=”text/javascript”>
    _uacct=”UA-xxxx-x”;
    urchinTracker();
    </script>

    …you would instead have something like this:

    <script src=”/scripts/jquery.js” type=”text/javascript”></script>
    <script src=”/scripts/jquery.gatracker.js” type=”text/javascript”></script>
    <script type=”text/javascript”>
    $(function(){
    $.gaTracker(‘UA-xxx-xx’);
    });
    </script>

  3. Thom Shannon says:

    I’ve been working an ASP.Net web control for GA, http://code.google.com/p/gacontrol/. One of the JS hacks I did for it was a way to inject campaign info by over riding a GA function, you might be able to make use of it, there’s also some stuff that adds querystrings to links and forms to track users across different domains for the same GA account. It could all be done better using jQuery though, I avoided libraries to keep a small footprint. Help yourself to any code that’s useful, http://gacontrol.googlecode.com/svn/trunk/GAControl/links.js

  4. Benjamin Sterling says:

    Jason,
    This is really nice, do you mind if I wrap it up in wordpress plugin, I have plugin now that does the same, but if I can go complete “jQuery” code I would like that better.

  5. Jamie Thompson says:

    It’s a nice little plugin. I was going to write it myself but it seems i don’t need to. One small thing though. As Colin has previously mentioned, it’s not taking advantage of the new GA API.

    ‘urchin.js’ is being replaced by ‘ga.js’ which is fully OO and contains many more advanced event tracking features. I quickly modified the plugin to pull in ‘ga.js’, and altered to the addTracking function accordingly. It seems to be working ok as far as i can tell.

  6. Colin says:

    @Jason … sorry for the delay. One issue is that Google seems to have deprecated the _trackEvent method, in favour of creating eventTrackers instead. Second, even whlie the _trackEvent() method is used, you seem to be passing an unused variable as the third paramater (“newLink”).

    I’ll try and post the modified code I’m currently using.

  7. Jason says:

    @Colin – I appreciate the input, but to be clear, these bugs do not exist in my original plugin code, which works with the deprecated urchin.js. The copy you’re working from was modified by someone else without my knowledge. I didn’t even know it existed until you linked to it. However, I’ll be sure to keep all of this in mind when I do finally get around to updating the plugin to support ga.js. Thanks!

  8. Colin Viebrock says:

    @Jason – no problem. I should’ve mentioned again that we weren’t using the 1.0.1 release, but the modified one.

    Something else I’m trying to figure out: how to manually add tracking events to links after gatracker is loaded and does it’s thing. I thought this would do it, but it doesn’t:

    $(‘#projectnav a’).each(function(p){
    $(this).click(function(){
    _gat._trackPageview(‘/somecode/’+p);
    });
    });

    I get “_gat._trackPageview is not a function”. Suggestions?

  9. Michel says:

    Hi jason.

    I tested gaTracker with outbound links and it work fine!

    First i had a problem with copy-paste the js from other site, but then simply i downloaded from your link and gaTracker worked ok!

    Simply to follow your basic steps:

    1. Download the origin gaTracker.js (a js functional and to avoid problems)
    2.

    $(function(){
    $.gaTracker(’UA-xxx-xx’);
    });

    3. Outbound links appear in google analytics-> content -> main content:

    /external/external-url/

    external-url is the “outbound link”

    Finally guy… thanks a lot!

  10. Blog Docentes On Line says:

    Google Analytics: Enlaces Salientes con Jquery…

    Google Analytics: Outbound Links con Jquery
    La técnica para el seguimiento de eventos y enlaces salientes, proporcionada por Google Analytics, se basa en la inserción de javascript en el enlace, ejemplo:
    <a href=‚Äùhttp://www.sitioexterno.com‚Äù …

  11. someone from the network says:

    Hi,

    You should see the “onClick” event modified in the source code of the page, isn’t it ?

    I’m trying to use your plugin without success (surely I’m doing something wrong)

    What I’ve done:

    1) put the .js code for the application.
    2) load the code in the section and call there:

    <script src=”webroot?>js/jquery.js” type=”text/javascript”>
    <script src=”webroot?>js/jquery.gatracker.js” type=”text/javascript”>

    $(function(){
    $.gaTracker(‘UA-xx’); <– my number ;-)
    //alert(‘done’);//debug
    });

    The following is more code, and includes, (also an old javascript calling google analytics with a different UA- number).

    Any advice ?

  12. Jason says:

    @someone:

    [quote]You should see the “onClick” event modified in the source code of the page, isn’t it ?[/quote]

    Not really. “View Source” for sure will not show it. I’m not even seeing it in Firebug in a site I checked just now, which surprised me, but I checked my Google Analytics and everything is definitely being tracked. Just keep an eye on your analytics account. Sometimes it takes a day or two before the results show up.

  13. Renan says:

    Hi Jason.

    This a awesome plugin, but older.
    When you use the new GA version?

    Thanks and don’t stop this job!

  14. anonymous says:

    >>>Unless you’ve been living under a rock

    Wow that’s funny. Not all of us code all night. Some of us have lives ;)

    I’m not nerdy enough? I find that comment interesting in a negative way in that it just shows the “Ego” that makes developers and IT a less than desirable work environment

  15. anonymous says:

    The instructions here are very misleading. Sure, I’ve poured over the JQuery ga plugin on the JQuery site but again this lacks in description.

    First off, I don’t understand if I need some sort of onclick event in all my hyperlinks that I define on my page in order for the extentions to work or what. I’ve tried just a simple link such as this in my .aspx page in my web project: TestPDF for Google Analytics

    I don’t know JQuery that well, but if I were to add an onclick (if needed) how would that be formed in relation to your function call?

    Ok, and once I click it, I get no GET in the request. When my page loads, I do get a GET, but just not when trying out the hyperlinks for resources such as pdfs, etc. that this plugin is supposed to support.

    Can you give us an example both on the .aspx or html side showing how your plugin works?

  16. anonymous says:

    In regards to the last post, it “appears” that you “don’t” need an onclick event on your hyperlinks and that all you have to do iis to make sure this is in every page:

    $(document).ready(function(){
    $.gaTracker(”);
    });

    or just

    $.gaTracker(”);

    I’ve tried both above with just the hyperlink example I gave in the previous post. The $.gaTracker(”); creates a GET but not for download hyperlinks or other related (mailto, etc.).

    So I’m confused here on how the download links are to be implemented in regards to your plugin code here: http://plugins.jquery.com/files/jquery.gatracker.js_0.txt

  17. anonymous says:

    So…can we get a FULL example sometime with both an .aspx or something showing both a regular post and an extensions post?

  18. a3cube says:

    I wonder why no one talk abt the option in all these comment….

    How do I customize the opts to a directory?

    Is it like this?

    $.gaTracker(
    ‘UA-XXXXX-XX’,
    {
    homepage: ‘/home/’,
    contact: ‘/contact/’
    }
    );

  19. andhapp says:

    Hey man,
    I just saw your timepicker jquery plugin. I just wanted to thank you for making it. Is it alright if I can go ahead and extend it and add unit tests. I will add it to github and send you a pointer to the repository. I just wanted to let you know. However, if you have any issuues with this, please ping me.

    Regards

  20. pHoEniX says:

    Hello. Do I need to remove the google analytics code from the footer if I use your plug-in? I am using the newest code available from google analytics.
    Thanks in advance.

    Regards

  21. vote.w3cvalidco.de says:

    Google Analytics Integration with jQuery…

    When you sign up for a Google Analytics account, you’re provided with a javascript code snippet which includes a unique account number, and you’re instructed to include this snippet on every page in your site that you wish to track. At a glance, this a…

  22. TVD says:

    Recently, I extended Google Analytics to add download tracking for Google’s new Asynchronous Google Analytics Model. I call the extension Entourage.js:

    http://techoctave.com/c7/posts/58-entourage-js-automatic-download-tracking-for-asynchronous-google-analytics

    One of my goals was a small footprint, so it’s narrowly scoped to track file downloads only – no mailto or external links. Also, it’s framework agnostic. I wanted developers to have the freedom to use the extension and still use whatever JavaScript framework they want.

    I love jQuery, but I’ve always had much respect for the MooTools and Prototype.js community too. Didn’t want them to have to load jQuery just to track file downloads.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>