Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics does not track link click events

I am currently using analytics.js (the newer version of GA) and I am trying to track all types of events from my website, including when a user clicks on an anchor tag pointing to an external URL. I am currently using this setup:

 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-KEY-HERE', { 'alwaysSendReferrer': true, 'allowAnchor': true });

and I send the events when hitting a link like this:

$(document).on("click", ".anchor-class", function (event) {
    label = //get data from anchor element here ...  
    ga('send', 'event', 'Link Clicked', 'Click Details', label);;
    return;
    }
});

and this does not send anything to GA (even though the event handler is calling the ga(send...) method). How ever, if I use this exact technique for but with event.preventDefault(); at the beginning of the function, the event is sent and it appears in GA dashboard.

Is there some setting that I missed in order to make this work properly?

like image 391
Tamas Ionut Avatar asked Oct 21 '22 16:10

Tamas Ionut


2 Answers

Use the hitCallback function:

  $(document).on('click','a', function(event){
    event.preventDefault();
    var label = $(this).attr('href');

    ga('send', 'event', 'Link Clicked', 'Click Details', label, {
      'hitCallback': function(){
        window.location.href = label;
      }
    });
  });
like image 178
Blexy Avatar answered Oct 24 '22 11:10

Blexy


As pointed out by Blexy, the correct way to do this is to use a hit callback. However, you also need to take into account that users may block Google Analytics using some privacy protection tool such as Ghostery, in which case the hit callback will never be executed. The following article explains how to implement this correctly:

http://veithen.github.io/2015/01/24/outbound-link-tracking.html

like image 35
Andreas Veithen Avatar answered Oct 24 '22 13:10

Andreas Veithen