对于一个新项目,我想使用 Google Analytics 4。
直到今天,我一直在使用普通的 Google Analytics,在我的隐私政策页面上,我有一个 Google Opt Out Cookie。
这是通过一个简单的 JavaScript 代码实现的。
代码是这样的:
<script>
// Set to the same value as the web property used on the site
var gaProperty = 'UA-XXXX-Y';
// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
window[disableStr] = true;
}
// Opt-out function
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
}
</script>
通过这段代码,我能够在我想要的页面上设置一个 Google Opt Out Cookie
<a href="javascript:gaOptout()">Click here to opt-out of Google Analytics</a>
所以现在我遇到了问题,新的 ga4 无法正常工作。在 ga4 的开发者页面上有一个禁用 ga4 的代码。
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script>
window['ga-disable-MEASUREMENT_ID'] = true;
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'MEASUREMENT_ID');
</script>
我必须如何设置按钮链接才能禁用 GA4?
有人可以帮我吗???
已经谢谢了,保持健康,享受你的生活:)
最佳答案
实际上,您在这里拥有大部分作品。
因此获取您的 GA4 测量 ID,类似于:249888888
GA4 代码中禁用测量的代码段是这样的:
window['ga-disable-MEASUREMENT_ID'] = true;
您需要将 MEASURMENT_ID
替换为您自己的 ID,在此示例中:249888888
将其与您自己的代码结合起来:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=249888888"></script>
<script>
// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-249888888';
if (document.cookie.indexOf(disableStr + '=true') > -1) {
window['ga-disable-249888888'] = true; //this is what disables the tracking, note the measurement ID
}
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '249888888');
</script>
// Opt-out function (this function is unchanged)
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
}
</script>
关于javascript - 如何为 GOOGLE ANALYTICS 4 设置 Google Opt Out Cookie - 不是通用的 - 新的 ga4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65274912/