Last active
November 3, 2020 19:16
-
-
Save adrianspeyer/af4e49cf0d6166ac341487506e6a4f56 to your computer and use it in GitHub Desktop.
Automatic Tracking Of Outbound Links for gtags.js
This file contains hidden or 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
<head> | |
<!--Need gtag.js code and jquery already in page --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> | |
<!-- Global site tag (gtag.js) - Google Analytics --> | |
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-1"></script> | |
<script> | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', 'UA-XXXXXXX-1'); | |
</script> | |
</head> | |
<script> | |
/** | |
* Function that automatically tracks a click on an outbound link in Google Analytics, | |
* using the gtags.js. Setting the transport method to 'beacon' lets the hit be sent | |
* using 'navigator.sendBeacon' in browser that support it. | |
* Please ensure you already have jQuery installed. | |
*/ | |
var trackOutboundLink = function(url) { | |
gtag('event', 'click', { | |
'event_category': 'outbound', | |
'event_label': url, | |
'transport_type': 'beacon', | |
'event_callback': function(){document.location = href;} | |
}); | |
} | |
</script> | |
<script> | |
jQuery(document).ready(function($) { | |
$('a[href^="http"]:not([href*="//' + location.host + '"])').on('click', function(e) { | |
trackOutboundLink($(this).attr("href")); return true; | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment