Monday, May 20, 2024
145
rated 0 times [  148] [ 3]  / answers: 1 / hits: 8405  / 3 Years ago, wed, march 31, 2021, 12:00:00

I want to add a custom script that integrates into an existing Tag Manager dataLayer on a page. I need this script to be notified about new dataLayer pushes.
So whenever something on the page uses window.dataLayer.push, my script should be informed about this.


Is there a way to add a custom dataLayer event listener to the Google Script API?


I am looking for something like


google_tag_manager.dataLayer.onPush(callback);

google_tag_manager.dataLayer.subscribers seems to list how many dataLayer subscribers there are - but how can I add my own?


More From » google-tag-manager

 Answers
5

JavaScript has a Proxy object with which you can set traps whenever an operation is executed on an object. Arrays are also objects and can be used with proxies.


When calling the push method on an array, a new value will be set to the array. So setting a trap for the set method should allow us to add behavior to the push method.


In the trap, create a CustomEvent event and dispatch it. You can name this event anything you want. Whenever a value has been added to the dataLayer array, an event will be emitted. You can listen from every file to this event to act on whenever a value is added to the dataLayer array.


With Reflect we can make sure that the original behavior of the push method is restored while keeping the added behavior.




window.dataLayer = window.dataLayer || new Proxy([], {
set: (obj, prop, value) => {
if (prop !== 'length') {
const pushEvent = new CustomEvent('datalayerpush', {
detail: value
});

window.dispatchEvent(pushEvent);
}

return Reflect.set(obj, prop, value);
}
});

window.addEventListener('datalayerpush', event => {
console.log(`Value pushed to dataLayer: ${JSON.stringify(event.detail, null, 2)}`);
});

window.dataLayer.push({
event: 'test'
});




[#1555] Saturday, March 27, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;