Created
August 15, 2017 11:26
-
-
Save Sleavely/8a9c401c7e912625cf4dfbf4aa7ab48e to your computer and use it in GitHub Desktop.
A nifty lil' snippet to wrap around .push() to observe what's being added to dataLayer.
This file contains 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
console.log('dataLayer before injection', window.dataLayer); | |
(function(){ | |
// Safeguard for sites that don't implement dataLayer or that haven't initialized it yet. | |
window.dataLayer = window.dataLayer || []; | |
// Keep a reference to the method we're overwriting | |
var existing_func = window.dataLayer.push; | |
window.dataLayer.push = function(){ | |
var args = arguments; | |
Object.keys(args).forEach(function(key){ | |
// Here is where we should look for args[key] entries that match our criteria. | |
// For now, we just print out whatever is being added. | |
console.log('Pushing to dataLayer', args[key]); | |
}); | |
// Now call the original method | |
return existing_func.apply(this, args); | |
}; | |
})(); | |
console.log('dataLayer after injection', window.dataLayer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For reference, this is how GTM.js does it: