Last active
September 25, 2023 18:21
-
-
Save jennatollerson/9d8b5aba535fc23dbe33b75f6778c4c7 to your computer and use it in GitHub Desktop.
Tracking outbound links in Google Analytics (Universal/GA3) without adding onclick attributes to all your anchors
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
// Standardish tracking code here at the top. | |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X"></script> | |
<script> | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', 'UA-XXXXXX-X'); | |
// Add this to track clicks on outbound links as events. | |
document.addEventListener("click", function (e) { | |
// On click, get the URL from the closest anchor. | |
var url = e.target.closest('a').getAttribute('href'); | |
// If href does not contain our domain, it's an external link. Track it. | |
if( url && url.indexOf( window.location.hostname ) < 0 ) { | |
gtag('event', 'click', { | |
'event_category': 'Outbound links', | |
'event_label': url, | |
'transport_type': 'beacon', | |
'event_callback': function(){document.location = url;} | |
}); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment