Alex Alex - 1 year ago 151
Javascript Question

Does Google Tag Manager "subscribe" to dataLayer.push? If yes, how?

When I push anything to datalayer (which is an array), does GTM notice that and push it directly to the Google Platform?

Or is it only happening once, when the GTM container is loaded?

If not, does GTM somehow subscribe to datalayer.push() ? Or is it just polling?

Answer Source

When you initialize GTM you pass the reference of you dataLayer object, which from that point on is replaced by an 'instance' of a special object managed by the GTM code. Compare what the chrome console tells you about the push method before and after you initialize GTM:


Before GTM


After GTM

When you push something to a GTM-initalized dataLayer, are actually calling a custom push method that informs it to the GTM code running on the client, if that push triggers a tag fire, it will result in a tag code being run, but it does not make any requests otherwise and is not sent to GTM servers or anything like that.

Observe that apart from pushes, there are many other events that GTM watches, such as clicks, form submits, DOM ready and even the container load, as you described.

You are not restricted to pushing events, you can (and in many cases should) push regular data (messages) and it will still be usable and visible on Google Tag Manager, just bear in mind that it needs an interaction to actually update its internal state (such as a click)

How they go about doing it, I do not know, but it could be done with something as simple as:

var dataLayer = [{name: 'Rui'}];

var DLWatch = (function(){
    var init = function(){
       window.dataLayer.push = push;

    var push = function(data) {
        window.dataLayer = window.dataLayer.concat([data]);
        console.log('Data pushed!');

   return {init: init};

dataLayer.push({foo: 'bar'});

To what you will get:

Data pushed!

And dataLayer will be


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download