Last active
September 9, 2015 15:11
-
-
Save heathdutton/21b1c00d48fa75195e9f to your computer and use it in GitHub Desktop.
Catch outbound links in Google Analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Safely track outbound links in Google Analytics using jQuery | |
*/ | |
(function($) { | |
"use strict"; | |
// Wait till the dom has loaded | |
$(document).ready(function(){ | |
// Current page host | |
var host = window.location.host; | |
// Click event on <a> tags within the body | |
$('body a').click(function(e){ | |
var link = $(this), | |
href = link.attr('href'), | |
target = link.attr('target'), | |
text = link.text().substring(140); | |
if ( | |
e.isDefaultPrevented() // Link already aborted | |
|| typeof ga !== 'function' // Google Analytics not (yet) loaded | |
|| link.length != 1 // Invalid link reference | |
|| href.length == 0 // Invalid href | |
|| host == link[0].host // Internal href | |
|| target == '_blank' // Target a new window, not truly outbound | |
) { | |
// Abandon course and follow usual click behaviour | |
// console.log('Abandoning outbound event for: ' + href); | |
return; | |
} else { | |
// Function to redirect to outbound page | |
function redirect() { | |
// console.log('Logging event for outbound link to: ' + href); | |
window.document.location = href; | |
} | |
// Cancel event and record outbound link | |
e.preventDefault(); | |
ga('send', { | |
'hitType': 'event', | |
'eventCategory': 'outbound', | |
'eventAction': 'link', | |
'eventLabel': href + ' - ' + text, | |
'hitCallback': redirect | |
}); | |
// Redirect after one second if recording takes too long | |
setTimeout(redirect, 1000); | |
} | |
}); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment