Skip to content

Instantly share code, notes, and snippets.

@lauripiispanen
Last active May 25, 2022 14:00
Show Gist options
  • Save lauripiispanen/628abc4facdc8f088525ac3bac31b0ef to your computer and use it in GitHub Desktop.
Save lauripiispanen/628abc4facdc8f088525ac3bac31b0ef to your computer and use it in GitHub Desktop.
Using ES6 proxies to keep historic data layer state for debug purposes
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