Last active
January 23, 2019 23:30
-
-
Save ctsstc/ccf4b787cda7149f4c9792af49d981ae to your computer and use it in GitHub Desktop.
Prevent GTM dataLayer from being redeclared or redefined / overwritten.
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
(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