Skip to content

Instantly share code, notes, and snippets.

@Rudis1261
Last active August 29, 2015 14:16
Show Gist options
  • Save Rudis1261/758422ecd7007c2795c2 to your computer and use it in GitHub Desktop.
Save Rudis1261/758422ecd7007c2795c2 to your computer and use it in GitHub Desktop.
This is to be able to inspect the url query string and send the details to Google Analytics through Google Tag Manager
<script type="text/javascript">
/*eslint-env browser*/
/*global ga*/
(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','//www.google-analytics.com/analytics.js','ga');
ga('create', '<API PROPERTY>', 'auto');
ga('send', 'pageview');
(function(u) {
'use strict';
function ucfirst(string) {
return string[0].toUpperCase() + string.slice(1);
}
function parseUrlQueryParams(string) {
var query = {};
var a = string.split('&');
var max = a.length;
for (var p = 0; p < max; p++) {
var b = a[p].split('=');
query[decodeURIComponent(b[0]).trim()] = decodeURIComponent(b[1]).trim();
}
return query;
}
if (u !== '') {
var URL = parseUrlQueryParams(u);
var needles = ['category', 'action', 'label', 'value', 'nonInteraction'];
var mustHave = ['category', 'action'];
var eventDetails = {'hitType': 'event'};
var validGaUrl = true;
var maxMustHave = mustHave.length;
var maxNeedles = needles.length;
for (var m = 0; m < maxMustHave; m++) {
if (typeof URL['event_' + mustHave[m]] === 'undefined') {
validGaUrl = false;
}
}
if (validGaUrl === true && typeof ga === 'function') {
for (var n = 0; n < maxNeedles; n++) {
if (typeof URL['event_' + needles[n]] !== 'undefined') {
var eventName = 'event' + ucfirst(needles[n]);
eventDetails[eventName] = URL['event_' + needles[n]];
}
}
ga('send', eventDetails);
}
}
}({{url_query}}, ga));
</script>
@quintonparker
Copy link

on line 14 i'd trim both the key and the value just to help with typos that might creep in

@quintonparker
Copy link

is parseQuery() expected to operate on document.URL

If so, it's going to miss the first parameter in a query string. Would need to slice the URL from the "?" before running thru parseQuery()

@quintonparker
Copy link

And wrap the whole thing in an anonymous function so as to manage var scoping

@Rudis1261
Copy link
Author

No, on GTM you can get the query string, and they provide is without the leading "?"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment