Reputation: 5419
I need to read cookie that are set by Google Tag Manager.
Right now if Google Tag Manager is loaded first time for end-user I can't read cookies (because it happens later, but not immediately).
Is there a good way (callback?) that can help me to read cookies once they are set? This issue is only relevant if user visits page first time.
Upvotes: 2
Views: 10954
Reputation: 852
From the discussion in the comments below the question, I would suggest the following solution (assuming you also send Pageviews to Google Analytics). Examples are based on Simo Ahava's (excellent) blog.
(Please note that I haven't had the opportunity to test it thoroughly, as I am currently unable to create a complete test case for this setup -- there might be some hiccups)
Reference: https://www.simoahava.com/analytics/macro-magic-google-tag-manager/#1-client-time
This will return the value for the cookie with name specified (be careful in where you use the value read, as there is always a chance that cookies are rejected by the User's browser policies).
Create a new Variable, with:
GA Cookie
_ga
(source: simoahava.com)
Reference: https://www.simoahava.com/analytics/macro-magic-google-tag-manager/#8-hitcallback-with-a-universal-analytics-tag & https://www.simoahava.com/analytics/macro-magic-google-tag-manager/#6-get-clientid-using-_ga-cookie
This callback function will be executed right after the Pageview is sent (i.e. after the _ga
cookie is set).
Create a Custom JavaScript Macro with the following code:
function () {
return function () {
// Code to be executed in order to read the cookie:
try {
var gaCookie = {{GA Cookie}};
// Do what you need to with the cookie here:
// ...
return gaCookie;
} catch (e) {
console.log('No Universal Analytics cookie found.');
return 'N/A';
}
}
}
This will execute the callback function you just defined right after the Pageview is sent.
In the Fields to set option of your Pageview Tag, set:
hitCallback
{{callBackFunction}}
Hope it can help you move forward.
Upvotes: 4