0

I want to parse a 'pushed' data layer string. I intend to use it to track click events and setup the appropiate funnels in Google Analytics, it looks as follows: products.view.19|view recent product|19

  • The first part (products.view.19) is the unique page identifier.
  • The second part (view recent product) is the action.
  • The last part is (19) is the action identifier, this way actions may be grouped and compared more easily.

So I did the following, I first created a trigger (it fires when a link has the tag 'data-trackclick' in it) which pushes the data value to a variable (variable for datalayer). However, now I want to split that variable in to 3 new variables, as described above. I selected 'javascript macro' for this but somehow it returns 'undefined'. The macro looks as follows:

function() {
  var data = {{TrackClickData}};
  var pieces = data.split('|');

  if (pieces[0].length()) {
      return pieces[0];
  } else {
      return data;
  }
}

Obviously this didnt work since it would only run on the initial load and not (like I thought) when the macro was requested, so it should somehow be fired on the 'click' and then set the variables accordingly.

Is this possible to do? Or do I really have to add the dataLayer.push() in script tags?

Enigmatic
  • 370
  • 2
  • 11

1 Answers1

0

A few things:

  • .length() is wrong, the property for array length is .length without the ()
  • if it exists, pieces[0] is not an array, then .length would return the string length, see How do you check for an empty string in JavaScript? for more standard way of checking for empty strings
  • Is this possible to do? There's virtually nothing you can't do with GTM, since you can write JavaScript code, you can do whathever you code allows you to do, and splitting a string to use parts of it as variables is certainly within the realm of possibilities.

My advise is to make your code work outside GTM first (eg test it in the browser console), then once it's all working, port it to GTM.

Max
  • 12,794
  • 30
  • 90
  • 142
  • Thanks for the feedback. I just changed 'length()' to 'length' and it still didnt work. Therefore I wrote my own webpack module for this and now I can easily add new dataLayer objects without too much of a hassle. – Enigmatic Aug 08 '18 at 17:19
  • 1
    length is not a method, it's a property. It is also a property of the string object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length). For strings it contains as value the number of characters (or rather, "code units"), for array the number of elements. – Eike Pierstorff Aug 08 '18 at 18:37
  • Thanks for correction Eike, updated my answer accordingly – Max Aug 08 '18 at 18:41