Skip to content

Instantly share code, notes, and snippets.

@ctsstc
Last active January 23, 2019 23:30
Show Gist options
  • Save ctsstc/ccf4b787cda7149f4c9792af49d981ae to your computer and use it in GitHub Desktop.
Save ctsstc/ccf4b787cda7149f4c9792af49d981ae to your computer and use it in GitHub Desktop.
Prevent GTM dataLayer from being redeclared or redefined / overwritten.
(function(win) {
var privateDataLayer = win.dataLayer || [];
Object.defineProperty(window, 'dataLayer', {
get: function() {
return privateDataLayer;
},
set: function(value) {
// Prevent looping when dataLayer has already been defined ie: dataLayer = dataLayer || []
if (value instanceof Array && value !== privateDataLayer) {
// In case there are multiple in the collection
// I don't know what crazy person would do this
value.forEach(function(val) {
privateDataLayer.push(val);
});
}
}
})
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment