From 7a270f75ec5d2bc64da4420c02448a3bf6be48e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89mile=20R=C3=A9?= Date: Fri, 24 Apr 2026 17:07:40 +0400 Subject: [PATCH] Fix Google Consent Mode integration for GTM / dataLayer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fall back to pushing consent commands onto window.dataLayer when window.gtag is not available, enabling compatibility with Google Tag Manager setups that don't define a global gtag function. Signed-off-by: Émile Ré --- .../cookie-banner/src/integrations/gcm.ts | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/cookie-banner/src/integrations/gcm.ts b/packages/cookie-banner/src/integrations/gcm.ts index 4350994c5..0530fb91d 100644 --- a/packages/cookie-banner/src/integrations/gcm.ts +++ b/packages/cookie-banner/src/integrations/gcm.ts @@ -22,18 +22,26 @@ export class GoogleConsentModeIntegration implements ConsentIntegration { ); } - private getGtag(): ((...args: unknown[]) => void) | null { + private getConsentFn(): ((...args: unknown[]) => void) | null { const w = window as unknown as Record; - const gtag = w.gtag as ((...args: unknown[]) => void) | undefined; - if (typeof gtag !== "function") return null; - return gtag; + + if (typeof w.gtag === "function") { + return w.gtag as (...args: unknown[]) => void; + } + + if (!Array.isArray(w.dataLayer)) return null; + + const dataLayer = w.dataLayer as unknown[]; + return function () { + dataLayer.push(arguments); + }; } setDefaults(categories: Category[]): void { if (!this.hasMapping(categories)) return; - const gtag = this.getGtag(); - if (!gtag) return; + const consentFn = this.getConsentFn(); + if (!consentFn) return; const defaults: Record = {}; for (const cat of categories) { @@ -44,7 +52,7 @@ export class GoogleConsentModeIntegration implements ConsentIntegration { } if (Object.keys(defaults).length > 0) { - gtag("consent", "default", defaults); + consentFn("consent", "default", defaults); } } @@ -54,8 +62,8 @@ export class GoogleConsentModeIntegration implements ConsentIntegration { ): void { if (!this.hasMapping(categories)) return; - const gtag = this.getGtag(); - if (!gtag) return; + const consentFn = this.getConsentFn(); + if (!consentFn) return; const update: Record = {}; for (const cat of categories) { @@ -67,7 +75,7 @@ export class GoogleConsentModeIntegration implements ConsentIntegration { } if (Object.keys(update).length > 0) { - gtag("consent", "update", update); + consentFn("consent", "update", update); } } }