当用户不想获取 cookie 时,我试图在 javascript 中阻止谷歌分析。
if (want_cookie != "no"){
/* load google analytics script */
}
但是我没有找到如何在javascript中加载这个脚本......
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX');
</script>
尝试这样的事情:
if (want_cookie != "no"){
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX");
document.documentElement.firstChild.appendChild(newScript);
}
所以我所做的是在检查用户是否同意 cookie 后动态创建脚本元素并将其附加到页面。
在已接受的答案的基础上,我像这样实现了它:
HTML:
<div id="declineButton">Decline</div>
<div id="acceptButton">Accept</div>
JS 拒绝:
declineButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = true; // replace G-XXXX with your id
});
接受JS:
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
}
注意: 根据 documentation,我们必须确保在执行
gtag()
之前完成禁用(设置窗口属性)。