Skip to content

Commit 522f2ae

Browse files
Merge pull request #8183 from DRafi2006/fix-gtm-consent
fix: respect cookie consent before loading GTM
2 parents 2485b6c + f9cb47f commit 522f2ae

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

‎gatsby-browser.js‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import "slick-carousel/slick/slick-theme.css";
55
export const disableCorePrefetching = () =>
66
process.env.NODE_ENV === "development";
77

8+
const STORAGE_KEY = "cookie_consent";
9+
810
document.addEventListener("DOMContentLoaded", () => {
911
/** init gtm after 3500 seconds - this could be adjusted */
1012
setTimeout(initGTM, 3500);
@@ -14,9 +16,20 @@ document.addEventListener("mousemove", initGTMOnEvent);
1416
document.addEventListener("touchstart", initGTMOnEvent);
1517
function initGTMOnEvent(event) {
1618
initGTM();
17-
event.currentTarget.removeEventListener(event.type, initGTMOnEvent); // remove the event listener that got triggered
19+
20+
if (window.gtmDidInit) {
21+
event.currentTarget.removeEventListener(event.type, initGTMOnEvent);
22+
}
23+
}
24+
25+
function hasGTMConsent() {
26+
return localStorage.getItem(STORAGE_KEY) === "accepted";
1827
}
1928
function initGTM() {
29+
if (!hasGTMConsent()) {
30+
return false;
31+
}
32+
2033
if (window.gtmDidInit) {
2134
return false;
2235
}
@@ -27,11 +40,21 @@ function initGTM() {
2740
// ensure PageViews is always tracked (on script load)
2841
script.onload = () => {
2942
window.dataLayer = window.dataLayer || [];
30-
window.dataLayer.push({ event: "gtm.js", "gtm.start": new Date().getTime(), "gtm.uniqueEventId": 0 });
43+
window.dataLayer.push({
44+
event: "gtm.js",
45+
"gtm.start": new Date().getTime(),
46+
"gtm.uniqueEventId": 0,
47+
});
3148
};
3249
script.src = "https://www.googletagmanager.com/gtm.js?id=GTM-PS26QB9";
3350
document.head.appendChild(script);
3451
}
3552

53+
window.addEventListener("cookie-consent-changed", (event) => {
54+
if (event.detail === "accepted") {
55+
initGTM();
56+
}
57+
});
58+
3659
export { wrapRootElement } from "./root-wrapper";
3760
export { wrapPageElement } from "./page-wrapper";

‎src/components/CookieConsent/index.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,13 @@ const CookieConsent = () => {
8282

8383
const handleResponse = (response) => {
8484
localStorage.setItem(STORAGE_KEY, response);
85+
86+
window.dispatchEvent(
87+
new CustomEvent("cookie-consent-changed", {
88+
detail: response,
89+
}),
90+
);
91+
8592
setOpen(false);
8693
};
8794

0 commit comments

Comments
 (0)