如何为 GOOGLE ANALYTICS 4 设置 Google Opt Out Cookie - 非通用型 - 新 ga4

Dig*_*alA 7 javascript cookies google-analytics google-analytics-4

对于一个新项目,我想使用 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>
Run Code Online (Sandbox Code Playgroud)

通过此代码,我可以在我想要的页面上设置 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>
Run Code Online (Sandbox Code Playgroud)

我必须如何设置 Button Link 才能禁用 GA4?
任何人都可以帮助我吗?

已经谢谢了,保持健康并享受生活:)

XTO*_*HEL 5

实际上,您在这里拥有大部分作品。

因此,获取您的 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>
Run Code Online (Sandbox Code Playgroud)


小智 5

对于 Google Analytics 4,我必须使用“G-”前缀来指示Measurement-ID。

window['ga-disable-G-XXXXXXXXXX']=true;

正如您在这里看到的: https: //support.google.com/analytics/answer/9539598?hl= en

在上面的例子中它必须是:



    ...
    // Disable tracking if the opt-out cookie exists.
    var disableStr = 'ga-disable-G-249888888';
    if (document.cookie.indexOf(disableStr + '=true') > -1) {
    ...