Building on top of the accepted answer, I implemented it like this:
HTML:
<button id="declineButton">Decline</button>
<button id="acceptButton">Accept</button>
JS for declining:
declineButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = true; // replace G-XXXX with your id
});
JS for accepting:
acceptButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = false; // replace G-XXXX with your id
appendScriptToHead();
executeGoogleAnalyticsScript();
});
function appendScriptToHead() {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://www.googletagmanager.com/gtag/js?id=G-XXXX"; // replace G-XXXX with your ID
document.head.appendChild(script);
}
function executeGoogleAnalyticsScript() {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-XXXX"); // replace G-XXXX with your id
}
Note:
According to the documentation we have to make sure that the disabling (setting the window property) is done before the gtag() is executed.