Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics - Outbound link tracking with a redirect

I have set up Google Analytics to track outbound links. However, I have also installed a WordPress plugin called Amazon Link Localizer that modifies the outgoing URL such that its final form is prourls.com?url=www.amazon.cominstead of www.amazon.com.

Is it possible to modify the Analytics script such that these outbound link clicks can still be tracked?

like image 387
zgall1 Avatar asked Apr 19 '18 02:04

zgall1


People also ask

Can Google Analytics track outbound links?

The onClick function will create an Event Category which will be outgoing_links, and the event action will be the URL. This should track all your outbound links. You can check this at the Content -> Events section when you go to your Google Analytics account.

How do I track outbound link clicks in Google track manager?

In the Google Tag Manager workspace, go to Variables → New. We'll create an Auto-Event Variable and select the variable type Element URL. The Component Type for this variable will be Is Outbound. This setting will check whether or not the clicked link is from the same domain on which Google Tag Manager is installed.

How does GTM track external links?

Tip 106: Track outbound link clicks with the Auto-Event variable. The method is simple. When you create a new Auto-Event variable in GTM, you can choose Element URL as the Variable Type. Without special modifications, this variable would return the value of the href attribute of the clicked link.


2 Answers

STEP 1: Add the trackOutboundLink script to your website.

Add this code in the <head></head> section of the page's HTML: (the full script is at the bottom of this page, but use this one to help minimize the page size)

<script>
var trackOutboundLink=function(t,e){var n,o="object"==typeof t?t.href:t,a=document.createElement("a");function c(){document.location=o}e=e||o,a.href=e,/\bprourls\.com?$/i.test(a.host)?e=(n=/[\?&]url=([^&#]+)/.test(a.search)&&RegExp.$1||"")?decodeURIComponent(n):e:/\blinksynergy\.com$/i.test(a.host)&&(e=(n=/[\?&]murl=([^&#]+)/.test(a.search)&&RegExp.$1||"")?decodeURIComponent(n):e),"function"==typeof gtag?gtag("event","click",{event_category:"outbound",event_label:e,transport_type:"beacon",event_callback:c}):ga("send","event","outbound","click",e,{transport:"beacon",hitCallback:c})};window.addEventListener("load",function(){var t,e,n=document.getElementsByTagName("a")||[];function o(t){t.preventDefault();var e=this.getAttribute("data-outbound-link");trackOutboundLink(this.href,"1"===e?"":e)}for(t=0;t<n.length;t++)(e=n[t]).href&&!/^#/.test(e.href)&&location.host!==e.host&&""!==e.getAttribute("data-outbound-link")&&e.addEventListener("click",o,!1)},!1);
</script>

Note that the script is a modified/customized version of the script provided by Google Analytics:

  • https://support.google.com/analytics/answer/1136920?hl=en — for the old analytics.js (or ga.js) library.

  • https://support.google.com/analytics/answer/7478520?hl=en — for the new gtag.js library.

STEP 2: Add data-outbound-link="1" to outbound links' HTML.

For each outbound links that you want to track, add this to the link's HTML:

data-outbound-link="1"

(And if you previously added onclick="trackOutboundLink('http://www.example.com'); return false;" to the link's HTML, then please replace it with the above code.)

So instead of: <a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>

..use this: <a href="http://www.example.com" data-outbound-link="1">Check out example.com</a>

THE FULL SCRIPT

Below is the full, unminified version of the custom trackOutboundLink script: (use this just for reference)

<script>
var trackOutboundLink = function(link, url2track) {
  var url2visit = ('object' === typeof link) ? link.href : link,
    a = document.createElement('a'),
    b;

  url2track = url2track || url2visit;
  a.href = url2track;

  // Dynamic redirect URLs via Prourls.com; this was for Amazon URLs.
  if (/\bprourls\.com?$/i.test(a.host)) {
    b = (/[\?&]url=([^&#]+)/.test(a.search) && RegExp.$1) || '';
    url2track = b ? decodeURIComponent(b) : url2track;
  // Dynamic redirect URLs via Link Synergy; this was for Footlocker URLs.
  } else if (/\blinksynergy\.com$/i.test(a.host)) {
    b = (/[\?&]murl=([^&#]+)/.test(a.search) && RegExp.$1) || '';
    url2track = b ? decodeURIComponent(b) : url2track;
  }
  // All other URLs are not parsed and expected to be valid outbound URLs.

  function onTracked() {
    //alert('Tracked: ' + url2track);
    document.location = url2visit;
  }

  if ('function' === typeof gtag) {
    gtag('event', 'click', {
      'event_category': 'outbound',
      'event_label': url2track,
      'transport_type': 'beacon',
      'event_callback': onTracked
    });
  } else {
    ga('send', 'event', 'outbound', 'click', url2track, {
      'transport': 'beacon',
      'hitCallback': onTracked
    });
  }
};

window.addEventListener('load', function() {
  var links = document.getElementsByTagName('a') || [],
    i, a;

  function _go(e) {
    e.preventDefault();

    // Track a custom URL address, if specified.
    var b = this.getAttribute('data-outbound-link');

    trackOutboundLink(this.href, '1' === b ? '' : b);
  }

  for (i = 0; i < links.length; i++) {
    a = links[i];

    if (!a.href || /^#/.test(a.href) || location.host === a.host) {
      continue;
    }

    if ('' !== a.getAttribute('data-outbound-link')) {
      a.addEventListener('click', _go, false);
    }
  }
}, false);
</script>
like image 123
Sally CJ Avatar answered Nov 14 '22 23:11

Sally CJ


Try this:

First, Remove the onclick handlers on all of your links.

Second Include the following code in your <head> block

var trackOutboundLink = function(url) {
    var newUrl = url;
    var re = /prourls\.co.*\?.*url=(.*)/
    var matches = url.match(re);
    if (matches && matches.length > 0) {
        newUrl = matches[1]
    }

    // console.log(newUrl);

    ga('send', 'event', 'outbound', 'click', newUrl, {
      'transport': 'beacon',
      'hitCallback': function(){document.location = url;}
    });
};

var btns = document.querySelectorAll('a.btn');
for (var i = 0, l = btns.length; i < l; i++) {
    btns[i].addEventListener('click', function(e) {
        // console.log(e.target.href);
        trackOutboundLink(e.target.href);
    });
}

Modified trackOutboundLink() now:

  • Checks if it is of the form prourls.com?url=XXXX
  • Extracts the value of the url parameter
  • Passes that value to the GA event tracking call
like image 25
vinoaj Avatar answered Nov 15 '22 00:11

vinoaj