Skip to content

Fix GA initialization before load #827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/spicy-impalas-swim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/integration-googleanalytics': minor
---

Initialize GA after script load
37 changes: 16 additions & 21 deletions integrations/googleanalytics/src/script.raw.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,14 @@
return '';
}

let disableCookies = false;
const cookie = getCookie(GRANTED_COOKIE);
if (cookie === 'yes') {
disableCookies = false;
} else if (cookie === 'no') {
disableCookies = true;
}
const disableCookies = getCookie(GRANTED_COOKIE) !== 'yes';

win[layer] = win[layer] || [];
win.gtag = function () {
win[layer].push(arguments);
};

win.gtag('js', new Date());
win.gtag('config', id);
// Consent must be configured before gtag is loaded, else it will be ignored
win.gtag('consent', 'default', {
ad_storage: disableCookies ? 'denied' : 'granted',
analytics_storage: disableCookies ? 'denied' : 'granted',
Expand All @@ -52,24 +45,26 @@
j.async = true;
j.src = `https://www.googletagmanager.com/gtag/js?id=${id}${dl}`;
j.onload = function () {
win.gtag('js', new Date());
win.gtag('config', id, {
send_page_view: false,
anonymize_ip: true,
groups: 'tracking_views',
...(disableCookies
? {
client_storage: 'none',
}
: {}),
...(disableCookies ? { client_storage: 'none' } : {}),
});
triggerView(win);

win.history.pushState = new Proxy(win.history.pushState, {
apply: (target, thisArg, argArray) => {
triggerView(win);
return target.apply(thisArg, argArray);
},
});
// Prevent pageview when consent is not granted. Necessary because the page_view
// event will set the _ga_<container-id> cookie, even with storage disabled
if (!disableCookies) {
triggerView(win);

win.history.pushState = new Proxy(win.history.pushState, {
apply: (target, thisArg, argArray) => {
triggerView(win);
return target.apply(thisArg, argArray);
},
});
}
};
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer');