javascript - 如何为 GOOGLE ANALYTICS 4 设置 Google Opt Out Cookie - 不是通用的 - 新的 ga4

标签 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>

通过这段代码,我能够在我想要的页面上设置一个 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/

相关文章:

jquery - 在浏览器的一个选项卡中设置的 Cookie 在其他选项卡中无法访问

google-analytics - 如何结合使用Google Analytics(分析)和Google AdWords gtag.js?

javascript - Google Analytics 在 knockout.js 数据绑定(bind)中推送 trackevent

java - 错误 : 'com.android.build.api.transform.TransformException: Error while generating the main dex list.'

javascript - JS support() 在 html 中显示标签

javascript - html 中的多个 javascript

javascript - 观看网站并等待事件

javascript - 调用在函数内部定义的函数

c# - 在 C# MVC3 中创建并读取 cookie 以确认登录用户

php - 每次加载页面时,使用新值更新存储在 cookie 中的数组