Tracking Events with Google Analytics

November 13, 2010

You can use the Google Analytics api to track events in your web application.

Clicking a Link

I wanted to track users that clicked on a link on my page. This link did a simple request to the backend which caused the page to refresh, but there's wasn't a separate url I could track through standard Google Analytics.

It's possible to track this by adding an onClick event to the link:

<a href="/contests/{{ContestEvent.contest.slug}}/{{ContestEvent.date_of_event}}/TakeOwnership/" 
     title="Click here to take ownership of this result, so you can modify it" 
     onClick="_gaq.push(['_trackEvent', 'User', 'TakeOwnership', '{{user.username}}']);">Take Ownership</a>

The call to _gaq.push takes some user defined parameters - here we're passing User for the category, TakeOwnership for the action and the current user's username for the value.

Logged In Users

We also wanted to track when users logged in. This is again tricky to do as the back end login processing in Django logs the user in the auto redirects to another page.

What we did was add some processing to our top level template to log an event against the user when any page is requested by a logged in user.

{% if user.is_authenticated %}
<script type="text/javascript">
  _gaq.push(['_trackEvent', 'User', 'PageView', '{{user.username}}']);
</script>
{% endif %}

Make sure you're using the latest tracking code:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'TRACKING_CODE']);
_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);
})();

References