raimtoon
raimtoon

Reputation: 725

How to retrieve value in different JS file from custom javascript variable in gtm

I’m trying to retrieve value in external javascript file from gtm.

The document structure is as below:

structure

In the index.js, I can find a json and want to get "signup/01" value in the json.

script

However I cannot see "signup/01" in (index).

index

Now, I tried to create a tag and custom javascript variable called pageStepId in gtm.

custom javascript variable

But I cannot get the value properly in the preview.

step id

And I have a custom javascript valuable in gtm and trying to get the value.

  var
    args = document.getElementsByTagName("script"),
    result = 0;
 
  for (var i = 0; i < args.length; i++) {
    var arg = args[i].innerText.match(/signup\/\d*/g);
 
    if (arg != null) {
      //result = arg[0].replace(/[^\d]/g, "");
      result = arg[0];
      break;
    }
  }
  return result;
}

I'm not sure if my approach is wrong or just a tiny mistake. Please help me.

Upvotes: 0

Views: 338

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

You seem to assume that the innerText will be the content of the linked file. Instead the innerText is empty (a script tag that links to an external file does not usually have an innerText).

What probably would work is to loop over the script tags, get the links to the file, load them via Ajax and inspect the response text to see if it contains the desired bits. But that turns an already ugly hack into a performance nightmare.

If you are very lucky, the variable you need is a global variable, in which case you could simple get the content by setting up a Javascript variable in GTM and adress individual properties of that object via dot notation. But then you probably already tried (and in any case, global variables do not usually have generic names such as "n").

Upvotes: 1

Related Questions