blog.1.image
February 09, 2023

Triggering a dataLayer event when the user accepts cookies with Cookiebot

by Justus

Cookiebot is one of the most popular cookie consent managers.
It does its job generally fine, but it severely lacks integration when used together with Google Tag Manager which I find a pretty significant oversight considering that GTM is by far the most popular tag management system.

While Cookiebot has a nice JavaScript API, it doesn’t offer a built-in event that really only fires when the user has actively clicked the “Allow all cookie” or “Allow selection” button.

The Cookiebot powered cookie banner on polaroid.com with the 'Allow selection' and 'Allow all cookies' buttons highlighted with a red outline. Above the outline, there is red text 'We only want a dataLayer event if these are actually clicked'

The CookiebotOnAccept event and the CookiebotCallback_OnAccept callback function may sound like they do that, but they are also triggered when an already-consented user loads the page which didn’t fit my particular use case.

So here’s how to trigger a dataLayer event when the user accepts cookies with Cookiebot:

<script>
;(function(){
    window.addEventListener("CookiebotOnAccept", function (e) {
        if (window.Cookiebot.changed) {
            window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                event: "cookiebot_accept"
            });
        }
    });
})();
</script>

This will fire a cookiebot_accept event in the dataLayer when the user

  • newly consents to all cookies
  • newly consents to the “current selection” with at least one available consent level active

It will not fire when the user

  • already consented to some or all cookies and simply loads the page
  • newly consents to the “current selection” with all consent levels inactive
  • declines or has declined all cookies

Use this at your own risk, considering that the window.Cookiebot.changed property is undocumented and may change at any time.

Did this article help you?

Then follow me on twitter
@justusbluemer
so you won't miss new articles here and for Web Analytics and Marketing technology updates in general :)