Auto-tag Outbound Links for Google Analytics


/ Published in: jQuery
Save to your folder(s)

This will automatically tag external links and prefix the URL with '/outgoing' for tracking in Google Analytics. The pageTracker is assumed to be added to the page elsewhere in the markup. By default it is applied to all links contained in the BODY tag, excluding those with the class 'noAutoLink.' This snippet is not an original work of mine, but I do not know its author.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. $(document).ready(function() {
  3. $('body a').filter(function() {
  4. var theHref = this;
  5.  
  6. if (theHref.hostname && theHref.hostname !== location.hostname) {
  7. $(theHref).not(".noAutoLink").attr('target', '_blank').bind('click keypress', function(event) {
  8. var code = event.charCode || event.keyCode;
  9.  
  10. if (!code || (code && code == 13)) {
  11. if (pageTracker) {
  12. var fixedLink = this.href;
  13.  
  14. fixedLink = fixedLink.replace(/https?:\/\/(.*)/, "$1");
  15. fixedLink = '/outgoing/' + fixedLink;
  16. pageTracker._trackPageview(fixedLink);
  17. }
  18. };
  19. });
  20. };
  21. });
  22. });
  23. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.