Skip to content

Instantly share code, notes, and snippets.

@MaKleSoft
Last active August 29, 2015 14:03
Show Gist options
  • Save MaKleSoft/9523481426b65e29b56c to your computer and use it in GitHub Desktop.
Save MaKleSoft/9523481426b65e29b56c to your computer and use it in GitHub Desktop.
GA and GTM
<!--
Add this as a custom html tag with a rule, that fires on all custom events. E.g.:
{{event}} matches RegEx .+
-->
<script id="gtm-tag">
(function() {
// Find and remove all gtm event tags
var gtmTags = document.querySelectorAll("#gtm-tag");
Array.prototype.forEach.call(gtmTags, function(tag) {
if (tag.parentNode) {
tag.parentNode.removeChild(tag);
}
});
})();
</script>
<!--
Add this as a custom html tag with the 'All pages' rule. Replace 'UA-XXXX-Y' with the Univeral Analytics Tracking-ID
-->
<script>
(function() {
// RFC4122-compliant uuid generator
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
// Load google analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','assets/ga.js','ga');
// Fetch or generate client id
var supportsLocalStorage = typeof localStorage !== "undefined",
clientId = supportsLocalStorage && localStorage.getItem("ga-clientid") || uuid();
if (supportsLocalStorage) {
localStorage.setItem("ga-clientid", clientId);
}
// Initialize GA
ga('create', 'UA-XXXX-Y', 'auto', {
storage: "none",
clientId: clientId
});
})()
</script>
<!--
Use this tag to actually send the event.
-->
<script id="gtm-tag">
// Send GA event
ga("send", "event", "Event Category", "{{event}}");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment