Pushing data to the right Google Tag Manager dataLayer namespace

It may happen that the site we’re tracking is using a custom dataLayer name, or that it’s using more than one Google Tag Manager accounts at the same time and therefore (it should) using 2 different dataLayer namespaces.  Most of people just push the info to window.dataLayer variable, but it could be window.myOwnDataLayerNS . So we’d need to adapt our dataLayer pushes to that variable name.

So we’re going to setup a Macro that is going to take care of returning the right dataLayer namespace name for our current container. This way we’ll not messing around with other’s containers namespaces and our scripts will work in any container even if we’re using a custom dataLayer name.

First, we’ll need to enable the “Container IDbuilt-in Variable within our container:

Now we’re adding a new variable, that will take care of reading the current “Container ID” and looking for it’s right dataLayer namespace. ( Remember, you’ll be able to find this macro code at the bottom of this post )

So, we should have now a new variable name {{getDataLayerNameSpace}} available in Google Tag Manager, that would be allow us to send the pushes to the right dataLayer variable for our current container, without the need to taking care of the variable name defined on the gtm snippet.

Then, we’ll be able to send the pushes to the dataLayer this way:


                              'eventValue','Some Event Value'

Did you have found this post useful ?, then go ahead and leave us a comment 🙂


 Macro Source Code

    var gtm_objects = [];    
    var gtm_counter = 0;    
    for (var i in window.google_tag_manager) 
        if (typeof(google_tag_manager[i]) == "object" && i.match(/^GTM-/)) {
            gtm_objects.push({'accountId': i});
        if (typeof(google_tag_manager[i]) == "object" && !i.match(/^GTM-/)) {
            gtm_objects[gtm_counter].dataLayer = i;
    for (var i in gtm_objects) 
       if (gtm_objects[i].accountId == "{{Container ID}}")
            return gtm_objects[i].dataLayer;

Author: David Vallejo

Google Analytics Consultant and implementer. I have some experience with Google Tag Manager Follow me: @thyng

Leave a Reply

Your email address will not be published. Required fields are marked *