Skip to content

Instantly share code, notes, and snippets.

@MatthewDaniels
Last active June 30, 2019 04:25
Show Gist options
  • Save MatthewDaniels/630caef135577df6d0cf002facb130ea to your computer and use it in GitHub Desktop.
Save MatthewDaniels/630caef135577df6d0cf002facb130ea to your computer and use it in GitHub Desktop.
Sends any GA hits to GTM for extra processing. Put this file directly after the ga create call.
/*
This code should be put directly after the ga create call, before any hits are fired to ensure
it captures all hits being sent to ga.
When any ga hit is fired, this code will capture it, fire the proper hit into GA and then forward
the hit query parameters to GTM via a dataLayer event.
The dataLayer event is called "gaHitTask" and the query parameters are sent in the "gaHitTaskParams" variable.
You can use code something similar to this: https://gist.github.com/MatthewDaniels/388fa1e0c02613f103f00a504ed58c55
to parse the gaHitTaskParams in GTM into a map to then use elsewhere in GTM - send to your GA for instance.
*/
ga(function(tracker) {
// Grab a reference to the default sendHitTask function.
var originalSendHitTask = tracker.get('sendHitTask');
// Modifies sendHitTask to send a copy of the request to GTM via a dataLayer event after
// sending the normal request to www.google-analytics.com/collect.
tracker.set('sendHitTask', function(model) {
// sends the original hit task to GA
originalSendHitTask(model);
// grab a copy of the hitPayload
var query = model.get('hitPayload');
// create the dataLayer variable if it does not exist
window.dataLayer = window.dataLayer || [];
// push an event with the name gaHitTask and the gaHitTaskParams as the query payload to the dataLayer for parsing in GTM
window.dataLayer.push({
'event': 'gaHitTask',
'gaHitTaskParams': query
});
///////////////////////////////////////////////
// REMOVE THESE CONSOLE LOGS FOR PRODUCTION
///////////////////////////////////////////////
// console.log('1:', query);
// console.log('2:', model);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment