📜 ⬆️ ⬇️

Outbound link tracking with Google Analytics

Google Analytics provides ample opportunities for collecting and analyzing site statistics, but, the way of tracking outbound links offered in the help center ...

<a href="http://www.primer.ru" onClick="javascript:urchinTracker('/outgoing/primer_ru');">

... To put it mildly, not very convenient.

Since the opportunity itself is very interesting, I decided to still use it and at the same time do without attaching onclick to each external link.

')

Plan


You can, of course, go through all the links on the page using JavaScript and attach the corresponding onclick handler to each one, but this is ugly, not optimal and does not work if the visitor does not click on the link to the image embedded in it. The technique of event delegation is very suitable for this case; one onclick handler attached to the document element will suffice.

Script


To simplify the script, the jQuery library was used, but fans of other frameworks can easily adapt it.
  <code> // function that determines if the link is external
 function isLinkExternal (link)
 {
     var r = new RegExp ('^ https?: // (?: www.)?'
         + location.host.replace (/ ^ www./, ''));
     return! r.test (link);
 }

 $ (document) .ready (function () {
    
     $ (document) .bind ('click', function (e) {
         // get the element with which the event occurred
         var target = (window.event)?  e.srcElement: e.target; 
        
         // click could be on the element embedded in the link
         // need to go up to the link itself
         while (target)
         {
             if (target.href) break;
             target = target.parentNode;
         }

         if (! target ||! isLinkExternal (target.href))
             return true;

         // track links in the form /outgoing/http/habrahabr.ru
         var link = target.href;
         link = '/ outgoing /' + link.replace (/: \ / \ //, '/');
         urchinTracker (link);
     });
    
     // as a bonus, we track clicks on the RSS links
     // although it will not give complete statistics on those who subscribed to us
     $ ('# feed-link'). bind ('click',
         function () {urchinTracker ('/ feed /');  });
     $ ('# fullfeed-link'). bind ('click',
         function () {urchinTracker ('/ fullfeed /');  });
     $ ('# commentsfeed-link'). bind ('click',
         function () {urchinTracker ('/ commentsfeed /');  });
 }); </ code> 


The script was developed by joint efforts on the forum htmlbook.ru

Other tricks to use Google Analytics can be found on the Design For Masters website in the Advanced Using Google Analytics article.

Source: https://habr.com/ru/post/13849/


All Articles