Last active
May 25, 2022 14:00
-
-
Save lauripiispanen/628abc4facdc8f088525ac3bac31b0ef to your computer and use it in GitHub Desktop.
Using ES6 proxies to keep historic data layer state for debug purposes
This file contains hidden or 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
let dataLayerHistory = [] | |
// this would come from GA | |
let dataLayer = { | |
push(obj) { | |
console.log("pushed to dataLayer", obj) | |
} | |
} | |
// here's our clever little trick... | |
window.dataLayer = new Proxy(window.dataLayer, { | |
get(obj, prop) { | |
if (prop === 'push') { | |
return function(v) { | |
dataLayerHistory.push({...v}) | |
return obj.push.apply(obj, arguments) | |
} | |
} else { | |
return Reflect.get(...arguments) | |
} | |
} | |
}) | |
// ... and now to test it | |
window.dataLayer.push({"foo": "bar"}) | |
window.dataLayer.push({"bah": "fuzz"}) | |
window.dataLayer.push({"foo":"baz"}) | |
console.log(dataLayerHistory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment