Shoora
10/18/2018 - 12:01 PM

Google Analytics outbound link tracking

Google Analytics outbound link tracking

/**
 * Outbound link tracking
 * -------------------------
 */
(function($) {
  // JS redirect function (because window.location doesnt add the referrer in the request header)
  function goTo(url, newtab) {
      var a = document.createElement("a");
      if(!a.click) //for IE
      {
           window.location = url;
           return;
      }
      a.setAttribute('href', url);
      a.style.display = 'none';
      if (newtab) a.setAttribute('target', '_blank');
      document.body.appendChild(a);
      a.click();
  }

  // attach on click event listener to all <a> elements
  $('a:not(.js-no-tracking)').on('click', function(e) {
    var url = $(this).attr('href');
    var sending = false;

    // abandon if link already aborted or analytics is not available
    if (e.isDefaultPrevented() || typeof ga !== 'function') return;

    if (e.currentTarget.hostname != window.location.hostname && !url.match(/^javascript\:/i)) {

      if (e.ctrlKey || e.shiftKey || e.metaKey || e.which == 2 || this.target == "_blank") {
        var newtab = true;
      }

      if (newtab) {
        // don't prevent link navigation for new tab links
       ga(
           'send', 'event', 'outbound link', 'click', url
       );
     } else {
       // for links that don't open in a new tab, navigate with JS after GA event has been sent out
       e.preventDefault ? e.preventDefault() : e.returnValue = !1;
       sending = true;
       //if after 300 ms the GA data still didnt get sent, redirect manually
      setTimeout(function() {
        if (sending) { goTo(url); }
      }, 300);

      ga(
         'send', 'event', 'outbound link', 'click', url,
         {
             'hitCallback': function() {
               sending = false;
               goTo(url);
             }
         }
      );
     }

    }
  });
})(jQuery);