0

i would like to track user behaviour on the website depending on they are logged in or not. I’d like to create my own variable in JavaScript, kind of userState with different values, let’s say, logged and guest, and I want to pass it so dataLayer. How to do it? Can I do something like this

dataLayer.push({‘userType’: userState})

?

webprogrammer
  • 2,393
  • 3
  • 21
  • 27

1 Answers1

0

Basically this will work. However, GTM will only update its internal state when a GTM event is registered. When you you dataLayer.push({‘userType’: userState}) the new value for userType will not be automatically available. It needs to be followed by an event, either one that is set up via a GTM auto event variable (such as gtm.click when you use a click trigger), or a custom event:

dataLayer.push({
  "userType": userState,
  "event":"updateUserState"
});

(also note that you use backticks in your example, which will give an error - you must use straight or double quotes).

A custom event is literally the key "event" with a custom value pushed to the dataLayer. GTM overwrites the push method of the dataLayer array to scan new pushes for the event keyword, and then updates the available variables within GTM.

Eike Pierstorff
  • 31,996
  • 4
  • 43
  • 62
  • Thanks for the answer! i'm kinda new in that stuff, so it's a little bit hard to undestand it, but i will try with developers to get things done. – Hummingbird Feb 12 '20 at 08:10
  • It's really not that hard. There is the dataLayer in the website, which is a Javascript variable. Then there is the internal state of GTM, which is in part fed from the dataLayer. Whenever the "event" keyword shows up in the dataLayer (either because there is a native GTM event, or because you pushed the keyword yourself) the content of the website dataLayer is merged into the internal state. Existing variables are updated with new values (if any, else they are unchanged), new variables are added to the internal state. – Eike Pierstorff Feb 12 '20 at 08:50