How To Track External Links As Events In Google Analytics

Event tracking in Google Analytics is extremely useful for tracking pretty much anything on your website. Use this code snippet to track all links to external websites. Note that this script does use jQuery, so you’ll need to include that as well as your regular Google Analytics tracking code. This script works best if you put it all the way in the bottom footer of every page.

<script>
jQuery("a").on('click',function(event){
	var thetarget = this.getAttribute('target')
    if (this.host !== location.host) {
		event.preventDefault();
		var thehref = this.getAttribute('href')
		var anchortext = this.text
		ga('send', 'event', 'outbound-article', thehref, anchortext);
		if (thetarget == "_blank"){
			var win = window.open(thehref, '_blank');
			win.focus();
		} else {
			window.location.assign(thehref)
		}
    }
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>