Google Tag Manager - Parse Dynamic Data Layer Variable

感情迁移 提交于 2021-01-29 08:38:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51747318/google-tag-manager-parse-dynamic-data-layer-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!