Aliaspooryorik
ColdFusion ORM Book

Track downloads and exit links with Google Analytics

Here's some handy code I just wrote for tracking in Google analytics clicked links which go to external sites or link to files which are being downloaded.


<html>
<head>
<!--- get jQuery from CDN --->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--- here is the extra link tracking code --->
<script type="text/javascript">
jQuery(function($){
// make sure the Google Analytics object is available
if (typeof _gaq === 'object') {

// listen to clicks
$('a[href]').click(function(){
if (this.href.indexOf('mailto:') === 0) {
_gaq.push(['_trackEvent','mailto','click',this.href.substring(7)]);
}
else if (this.href.match(/\.(pdf|doc|zip|ppt|exe|xls|docx)$/)) {
_gaq.push(['_trackEvent','download',listLast(this.href),this.href]);
}
else if (this.href.match(/\.(avi|mov|wmv|flv|f4v|mp4)$/)) {
_gaq.push(['_trackEvent','video',listLast(this.href),this.href]);
}
else if (this.href.match(/\.(mp3|wav|aac|wmf)$/)) {
_gaq.push(['_trackEvent','audio',listLast(this.href),this.href]);
}
else if (!this.href.match(document.domain)) {
_gaq.push(['_trackEvent','exit','click',this.href]);
}
});
}

// utility function to get the file extension
function listLast( list ){
return list.split('.').pop().toLowerCase();
}
}
});
</script>
<!--- This is your normal Google analytics tracking code --->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456-0']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>

<p>All of these links will be reported in Google analytics when clicked</p>

<ul>
<li><a href="assets/downloads/myfile.pdf">PDF download</a></li>
<li><a href="http://www.amazon.co.uk/registry/wishlist/2KF8E1V3S0BU0">John's Amazon Wish List</a></li>
<li><a href="mailto:someguy@adomain.foo">mail me</a></li>
</ul>

</body>
</html>

2 comments

  1. Usefull.

    One small improvement i would suggest is to detect enter key ups on links as well and record these as a 'key press'', otherwise your missing out on traffic data.

    Comment by Chris – April 11, 2012
  2. Thanks! I can you use right away!

    Comment by Marcus C. – April 11, 2012

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts