Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

Google Tag Manager - read cookie just after they are set

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

Answers (1)

Philippe Sawicki
Philippe Sawicki

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)

1. Create a Variable to read the _ga cookie

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:

  • Variable Name of GA Cookie
  • Cookie Name of _ga

Reading Cookies with Google Tag Manager
(source: simoahava.com)

2. Define a callBackFunction

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';
      }
   }
}

3. Define a hitCallback after sending the Pageview

Reference: https://www.simoahava.com/analytics/macro-magic-google-tag-manager/#8-hitcallback-with-a-universal-analytics-tag

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:

  • Field Name to hitCallback
  • Value to {{callBackFunction}}

Setting "hitCallback" functions in Google Tag Manager


Hope it can help you move forward.

Upvotes: 4

Related Questions