Google Analytics Integration with jQuery
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'
]
}
);






[...] gaTracker, es un plugin desarrollado sobre jQuery con el que podemos inter√°ctuar con las opciones que Google Analytics nos ofrece y que seguramente no conocemos. [Descargar] Comp√°rtelo # « Nace GenFavIcon, para generar favicon’s online [...]
fantastic job… this will be incredibly useful!
That’s really a nice idea. Thanks for sharing.
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…
@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>
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
[...] Wheel 2.0: Jason Huck?s Devblog » Google Analytics Integration with jQuery – [...]
Awesome, I really wanted to do something like this. Thanks.
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.
[...] Wheel 2.0: Jason Huck’s Devblog » Google Analytics Integration with jQuery (tags: jquery analytics google javascript plugin stats) [...]
@Benjamin Sterling – By all means, go for it.
[...] Google Analytics Integration with jQuery interesting plugin, I know there are some issues with file downloads and google analytics being used the old fashioned way (tags: google javascript jquery) [...]
Yep – I would agree with that.. Thanks for the line.
This is great, but there seem to be issues with it. I know you don’t support the new GA tracking code yet, so I looked at your code at https://openid.trustbearer.com/support/jquery.gatracker.js but there are some errors/oversights in that code too.
Do you have a working (even BETA) version of jquery.gatracker.js that works?
@Colin – Could you be more specific about the problems you’re seeing? While we don’t have this in widespread use yet, it is deployed on several of our sites and seems to be working just fine for us. Are you using version 1.0.1 from here? http://plugins.jquery.com/project/gaTracker
- jason
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.
@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.
It’s not the most elegant, I know, but … http://pastebin.com/f64de11fe
@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!
@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?
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!
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‚Äù …
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 ?
@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.
Hi Jason.
This a awesome plugin, but older.
When you use the new GA version?
Thanks and don’t stop this job!
>>>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
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?
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
So…can we get a FULL example sometime with both an .aspx or something showing both a regular post and an extensions post?
[...] all the features of Jason Huck’s GA jQuery integration [...]
[...] numerous requests, I have either been too busy or too lazy, or both, to update my gaTracker plugin to support the new ga.js script from Google Analytics. Hence, I am very interested in trying out [...]
[...] Huck makes Google Analytics even easier to implement thanks to jQuery. Currently the plugin does the [...]
umm.. you write a plugin but your blog doesn’t even use it?
[...] Interesante artículo de Integración de Google Analytics con jQuery. [...]
[...] all the features of Jason Huck’s GA jQuery integration [...]
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/’
}
);
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
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