Skip to content

Instantly share code, notes, and snippets.

@iampatgrady
Last active November 17, 2017 20:36
Show Gist options
  • Save iampatgrady/276790adab86fd6a7d17a01e28db2bb0 to your computer and use it in GitHub Desktop.
Save iampatgrady/276790adab86fd6a7d17a01e28db2bb0 to your computer and use it in GitHub Desktop.
Convert Classic GA integrations to work with new Universal or GTM
// Code Example taken from Jeff Pierce's dataLayer Inspector+ Chrome Extension
// https://chrome.google.com/webstore/detail/analytics-pros-datalayer/kmcbdogdandhihllalknlcjfpdjcleom?hl=en-US
// create the handler object, and initialize the _gaq array
var a = window["_gaq"] = window["_gaq"] || [];
// for Data Layer Support:
window.dataLayer = window.dataLayer || [];
// b() is where you invoke business logic as a result of data pushed in _gaq
function b() {
// in this case, the integration is the Custom Search Engine: https://cse.google.com/cse/
// the CSE integration pushes this data: _gaq.push(['_trackPageview', '/page/url?q=search+term'])
// check if the push is a pageview
if (arguments[0][0] == "_trackPageview") {
// for Universal GA:
ga('send', 'pageview', arguments[0][1]);
// for GTM dataLayer:
dataLayer.push({
"event": arguments[0][0],
"page": arguments[0][1]
});
}
}
// "Monkey Patch":
//Given an object, an array in this case, you save the original function call (push) to a variable
var c = a.push;
// Replace the function with your own (monkey patch: a.push
a.push = function() {
// that calls your code
b.apply(this, arguments);
// and the original function
c.apply(a, arguments)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment