Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No analytics cookies is set upon a consent was updated

I am using the Google Tag Manager with a single tag referencing a default Google Analytics script. My solution is based on the information from these resources:

  • https://www.iubenda.com/en/help/27137-google-consent-mode
  • https://www.simoahava.com/analytics/consent-settings-google-tag-manager/
  • https://www.simoahava.com/analytics/consent-mode-google-tags/

The code is simple (commit):

index.html: define gtag() and set denied as a default for all storages

  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { window.dataLayer.push(arguments); }
    gtag('consent', 'default', {
      ad_storage: 'denied',
      analytics_storage: 'denied',
      personalization_storage: 'denied',
      functionality_storage: 'granted',
      security_storage: 'granted',
      wait_for_update: 400,
    });

Then load a user configuration from the localStorage and call update:

handleCookies(preferences) {
  console.log('handleCookies callback');
  gtag('consent', 'update', {
    ad_storage: preferences.ad,
    analytics_storage: preferences.analytics,
    personalization_storage: preferences.personalization,
  });
  console.log(window.dataLayer);
},

So far so good because I see the event queue is updated in dataLayer:

chrome console

As the consent is set I anticipate the the cookies will be set for the Google Analytics now. But they are missing. What stupid mistake have I done?

cookies box

GTM configuration

like image 904
Leos Literak Avatar asked Feb 03 '23 13:02

Leos Literak


2 Answers

Your update command happens after the GTM container snippet is rendered by the browser, so the update command is processed only after the All Pages trigger has already been processed.

You need to either delay your tags to fire on a later trigger (e.g. DOM Ready) or change how your script works to push the 'update' command sooner.

Alternatively, you can use the Consent Mode tag template found in the template gallery to orchestrate everything through GTM. The template uses GTM's synchronous consent APIs which ensure that the consent state is applied immediately rather than only once the dataLayer queue is processed.

like image 198
Simo Ahava Avatar answered Feb 06 '23 07:02

Simo Ahava


From your screenshot, gtm.js is executed before the update of the consent mode so the pageview continues to be sent to Google Analytics as denied.

The update must take place before gtm.js

like image 23
Michele Pisani Avatar answered Feb 06 '23 09:02

Michele Pisani