Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics Async: Events Tracking Callback?

I wish to use event tracking to record clicks on a specific type of link to another website. I am using jQuery, and the code I currently have is:

$('a.website').click(function(event) {
    var href = $(this).attr('href');
    try {
        _gaq.push(['_trackEvent', 'website', 'click', href]);
    } catch(err) {}
});

However, after seeing referrer information from the other site, I don't belive this is accurately tracking the clicks, probably because _gaq.push is asynchronous, and the request has not been received before the browser navigates to the url, and terminates any javascript running on the current page.

Is there any way to detect that the _gaq.push function has completed successfully, so I can use event.preventDefault() and document.location to navigate to the link after the event has been recorded?

like image 745
Matt Austin Avatar asked Nov 16 '11 05:11

Matt Austin


People also ask

How do I know if Google Analytics event tracking is working?

To see if Google Analytics is firing on your page, go to any page on your site in your Chrome Browser and right-click. Click on Inspect. Then go to the Network tab. Hit refresh on your browser and watch to see the different content and scripts loading on the page.

Why are events not showing up on Google Analytics?

If your events aren't showing up in Google Analytics, there are a few common issues you should look for. Are you using the correct api_secret? Check that you're using the api_secret for the right stream. If you set up the measurement protocol for multiple streams, each stream will have its own secret.

What can Google Analytics event tracking be used for?

Google Analytics event tracking is an advanced feature that allows you to track a specific user's interaction/activity (link clicks, downloads, form submission and video plays) with a web page element.


2 Answers

Use Google Analytics hitCallback

You can set a custom callback on the tracker object by using:

_gaq.push(['_set', 'hitCallback', function(){}]);

I described the code for it a little more in-depth here: Track event in Google Analytics upon clicking form submit

like image 79
flu Avatar answered Oct 19 '22 17:10

flu


How about solution from this answer?

  // Log a pageview to GA for a conversion
  _gaq.push(['_trackPageview', url]);
  // Push the redirect to make sure it happens AFTER we track the pageview
  _gaq.push(function() { document.location = url; });
like image 36
fliptheweb Avatar answered Oct 19 '22 18:10

fliptheweb