Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Created August 15, 2017 11:26
Show Gist options
  • Save Sleavely/8a9c401c7e912625cf4dfbf4aa7ab48e to your computer and use it in GitHub Desktop.
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.
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);
@Sleavely
Copy link
Author

For reference, this is how GTM.js does it:

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