Reputation: 161
I can read first party cookies that have set names just fine in Google Tag Manager. However I have come across a few instances where the cookie name is session based and there isn't a name set consistently for me to check against. I want to know if the cookie is set and ideally read the data.
For instance cookie_name_123456 cookie_name_234567 cookie_name_345678
It doesn't look like the name field takes regular expressions. Anyone know a way to setup GTM to read a cookie like that?
Upvotes: 0
Views: 1617
Reputation: 32760
You can create a custom HTML tag with a Javascript that reads the document.cookie property, and split in by the delimiter to get an array with individual cookies (document.cookie.split(";")
).
This gives you an Array with all first party cookies that are not flagged as "http only" (those are not accessible with JS). Each array entry will have the format of "cookiename equals value" (e.g. "_ga=GA1.2.1545993750.1587886865
" would be the Universal Analytics cookie "_ga
" with a client id as value). You can then loop over the array.
Inside the loop you can split each array entry by the "=" sign to get arrays with two elements, [0] for name and 1 for value. You then apply your regex to the name. If the rexeg matches what you are looking for, you can push the value to the dataLayer.
To make sure this has run before the tag that will be using the cookie value, you can use tag sequencing. If you manage your sequence via the onHtmlSuccess() and onHtmlFailure() functions as explained e.g. here in Simo's blog you can set the sequence so that the tags are only fired when the cookie value is actually there.
Alas it is not possible to do this in a custom template, which would be so much more elegant, but the sandboxed JS inside custom templates cannot access global document properties.
Upvotes: 1