Google Analytics Events Not Tracking

/

Recently I had to add some custom event tracking to a website via Google Analytics. Following the simple instructions on the analytics site, I setup some JavaScript to fire off when specific links were clicked. Note this is using their Universal Analytics which is a newer version of the platform.

I was using their own jQuery example for sending events:

$('.button-class').on('click', function() {
  ga('send', 'event', 'button', 'click', 'my-label');
});

Yet, on my site, these events were not being recorded in the Analytics. Problem.

After some inspection via the Chrome Network Panel, it looked like the send event was cancelled as the link was being followed to the new page.

Sure enough it looked like the analytics event firing process was initiated, but then cancelled as the link went to reload a new page. I could understand the browser handling an asynchronous event in this manner, cancelling all unfinished events on a page if a new page is loaded.

As JavaScript moves more towards more and more asynchronicity, it is usually worth looking into initially as a potential cause for any events, networking or timing problems.

My next task was to figure out how to delay the next page load till the Analytics event tracking call was finished. Luckily the event sending method in ga offers a way to get into the asynchronous return, which is all we need to add some control flow to prevent the page from moving along till we know the event tracking has executed successfully.

$('a.special-link-to-another-page').on('click', function eventTrackClick(event){
  event.preventDefault();
  var eventTarget = this;
  ga('send',{
      hitType : 'event',
      eventCategory : 'link',
      eventAction : 'click', 
      eventLabel : 'Special Link Was Clicked',
      hitCallback : function(){
        $(eventTarget).off('click', eventTrackClick);
        eventTarget.click();
      } 
  });
});

The purpose of this code is to override the click event on the target link to ensure the ga event tracking is properly executed once per link click. There is a good amount of stuff happening in the code:

  • jQuery to select all the links I wanted tracked
  • Setup the link tracking function:
  • On click, .preventDefault() : stop the click from going through
  • Store eventTarget (the clicked link itself) in the closure
  • Send the Analytics event
  • Use the hitCallback callback to:
  • Remove the current callback eventTrackClick from the link's click event handler
  • Fire another click to do whatever was going to happen (page reload)

Now if the Google Analytics event send never executes the callback the next page will never load. But I tend to discount the probability of an error out of Google infrastructure. I could wrap an overriding timer around it should the callback become an issue.