如何设置谷歌分析 4(GA4)的谷歌 Opt Out Cookie,而非通用的 Opt Out Cookie

7

我想在一个新项目中使用Google Analytics 4。

直到今天,我一直在使用普通的Google Analytics,在我的隐私政策页面上添加了一个Google Opt Out Cookie。该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()">点击此处选择退出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?有谁能在这里帮助我吗?谢谢,保持健康,享受生活 :)
2个回答

5
为了使用Google Analytics 4,我必须在Measurement-ID前面添加'G-'前缀。
如下所示: window['ga-disable-G-XXXXXXXXXX']=true; 您可以在这里查看:https://support.google.com/analytics/answer/9539598?hl=en 在上面的例子中,必须是:


    ...
    // 如果opt-out cookie存在,则禁用跟踪。
    var disableStr = 'ga-disable-G-249888888';
    if (document.cookie.indexOf(disableStr + '=true') > -1) {
    ...



5

您已经拥有大部分的组件。

获取您的GA4测量ID,它看起来像:249888888

禁用测量的GA4标签中的代码片段如下:

window['ga-disable-MEASUREMENT_ID'] = true;

您需要使用自己的ID替换MEASURMENT_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>

嘿XTOTHEL,感谢您的回复。我的测量ID以字母开头,看起来像G-M7562N73457之类的东西。 不幸的是,这个代码不起作用...我收到了没有跟踪的信息。 - DigitalA
你在自己的项目中尝试过这段Google Analytics 4代码吗? - DigitalA
嘿,是的,使用G-M756等,我意识到“disableStr”未声明。 - XTOTHEL
如果您能发布完整的代码,那将非常棒。 - DigitalA
我尝试了您提供的解决方案,即对GA(UA-XXXXX-Y)和GA4(29888888)都使用window['ga-disable-XXXXX']=true,但似乎无法阻止对Google Analytics API的调用。 - AlexandreS
@DigitalA 如果你按原样复制了代码,可能是因为早期的 </script> 关闭标签导致你的代码无法工作。否则,这是对这篇帖子的正确答案。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接