简体   繁体   中英

Javascript variable undefined when used in data layer in GTM

I am using a variable in GTM data layer which retrieves its value from Liferay rest API call.

var openId;
AUI().ready('aui-base', function(A){
Liferay.Service(
       '/user/get-user-by-id',
        {
        userId: Liferay.ThemeDisplay.getUserId()
        },
        function(obj) {
          openId=obj.openId;
        }
                );
    });

Here the openId variable is being used in GTM dataLayer,where it is not available and shows as undefined . The data layer is defined as below:

dataLayer = [{
                "page" : Liferay.currentURL
                ,"pageType" : instrDetail
                ,"user" : {
                            "type" : userType
                            ,"accountId" : openId
                          }
             }];

and in the end,we have the GTM block,defining the tag manager script block.

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');

Now,when I try to access the openId variable in dataLayer,it shows as undefined,whereas when I try to access the same one browser console,it displays the correct value.

This was solved after attempting twice.

Firstly after some searching up,I came across this fact that this was a Javascript asynchronous issue.The dataLayer was fetching the variable before the Rest call response was received and hence the variable was unavailable in dataLayer(being retrieved before time) and was available in page post that.In order to sort this up,the dataLayer had to be constructed,after successfully receiving the response.Hence,a callback function was called,containing dataLayer ,after successfully receiving the response

AUI().ready('aui-base', function(A){
Liferay.Service(
       '/user/get-user-by-id',
        {
        userId: Liferay.ThemeDisplay.getUserId()
        },
        function(obj) {
          callback(obj.openId);
        }
                );
    });

But then another issue came up,now the GTM script block was executing on page load,before rest API response,hence all other variables became undefined .This was due to the fact,that now datalayer was not available to GTM script,before response from REST call.

To sort this up,both the dataLayer and GTM script block had to be part of callBack function and called after response is successfully received.This finally solved the issue.

function callback(openId)
    {
      dataLayer = [{
                "page" : Liferay.currentURL
                ,"pageType" : instrDetail
                ,"user" : {
                            "type" : userType
                            ,"accountId" : openId
                          }
                  }];
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
 })(window,document,'script','dataLayer','GTM-PGLDG7W');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM