To pull data from the Data Layer using the GTM object command with Javascript

vijay khamitkarvijay khamitkar
2 min read

Sometime, we need GTM object value to manipulate HTML DOM element as per DataLayer value loaded. Here is the trick to pull the data from the Data Layer object using Javascript

We need to install Tag Assistant Legacy (by Google) extension for Chrome so we can easily check the Datalayer Object and Google Tag Manager (GTM) Container name from where we need to pull data.

Url to install Tag Assistant Legacy (by Google) for Chrome

https://chrome.google.com/webstore/detail/tag-assistant-legacy-by-g/kejbdjndbnbjgmefkgdddjlbokphdefk?hl=en

** for other browsers we can search the extension with browser names.

Syntax :

google_tag_manager[“Container_ID”].dataLayer.get(“key”);

Example for Maruti Suzuki website URL. (https://www.marutisuzuki.com/channels/arena/all-cars)

When we open the above URL in chrome and click on extension of Google Tag Assistant Legacy so we can see all GTM containers ID loaded for that page. Once we navigate to GTM-KZ5HNDG container Id, > Data Layer tab, It will show all Data Layer object loaded for the container.

If we need to pull Data Layer object value for key "gtm.scrollDirection" (refer above screenshot), then we can write Javascript code as mentioned below.

It is always best practice to write a code inside the try...catch statement to handle the error if GTM container doesn't load or failed to load

     try {
            var dl_value=google_tag_manager['GTM-KZ5HNDG'].dataLayer.get('gtm.scrollDirection') ||  0; // 0 is assign if value is undefined

            if(dl_value === undefined || dl_value === 0 ){
                console.log(`${dl_value} is not set`);
            }else{
                console.log(`${dl_value} is set`); //vertical is set
            }
        } catch (error) {
            console.log(error);
        }

Hope this will helpful!!!

0
Subscribe to my newsletter

Read articles from vijay khamitkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

vijay khamitkar
vijay khamitkar