Reputation: 4095
I am using google analytics with GTM.
Currently I am using a data layer variable in the fields to set.
I would like to change it to take a value from cookie, so I set up a cookie variable.
But the problem is that my cookie is stringified json so I need to parse it and take specific property form it.
The cookie looks like that:
I need to take the value form the cookie (already set up variable in gtm {{user cookie}}. I need to parse it (JSON.parse
) and then take userId prop from the parsed json and use it in the google analytics user field.
Upvotes: 0
Views: 1403
Reputation: 32760
You would have to use a custom JavaScript variable. That takes the form of an anonymous function that returns a value (or at least includes an return statement, technically it can return null or undefined). This would look something like:
function() {
var myJson = JSON.parse("user cookie");
return myJson.userId
}
On disadvantage is that this will do a JSON.parse every time the variable is evaluated, which may come with a performance hit. One way around this would be to use a custom HTML tag that is fired once per page, parse the cookie, iterate over the values and push them to the dataLayer (this might lead to timing problems, you might have to use tag sequencing to make sure your cookie is parsed before you try to use the value).
Upvotes: 1