Shoora
7/28/2014 - 2:06 PM

Outbound Link Tracking

Outbound Link Tracking

(function(){
  // Provides a plugin name and constructor function to analytics.js. This
  // function works even if the site has customized the ga global identifier.
  function _providePlugin(pluginName, pluginConstructor) {
    var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
    if (ga) ga('provide', pluginName, pluginConstructor);
  }
  
  // Creates the plugin to tag outbound link
  function outboundConstructor(tracker, config){
    var d = document,
        ownDomain = config['ownDomain'] || d.location.hostname;
        
    var fnc = function(event){
      try{
        if (!event || !event.target) {
          event = window.event;
          event.target = event.srcElement;
        }
        var el = event.target;
        if (el && el.href && el.href.indexOf(ownDomain) < 0) {
          if (event.preventDefault) {event.preventDefault();}
          else {event.returnValue = false;}
          
          var do_redirect = function(){
            window.location = el.href;
          };
          
          // Redirects anyway after 2 seconds if something goes wrong
          setTimeout(do_redirect, 2000);
          
          tracker.send('event', 
            'Outbound', 
            el.href.match('[^/]+//([^/]+)')[1], 
            {
              'hitCallback': do_redirect
            }
          );
        }
      } catch (e) {
        tracker.send('event', 'Javascript Error', 'GA Outbound Link Tracking');
      }
      
    };
    
    // W3C model
    if (d.addEventListener) {
        d.addEventListener('click', fnc, false);
        return true;
    } 
    // Microsoft model
    else if (d.attachEvent) {
        return d.attachEvent('onclick', fnc);
    }
  
  }
  
  _providePlugin('outbound', outboundConstructor);
})();