切换谷歌分析 - 选择退出/选择加入

Toggle google analytics - opt out / opt in

本文关键字:选择 退出 谷歌      更新时间:2023-09-26

我已经实现了Google analytics Opt out功能,但我真正需要的是用户undo他的操作的选项。

Lats说,用户点击按钮选择退出,但随后改变了主意。无论如何,我们都希望进行跟踪,因此用户可以选择再次启用跟踪是一件好事。

我遇到的问题是不确定如何处理这个问题。这篇文章的末尾是jsFiddle示例。我正在做的是最初包括跟踪代码,然后optionally creating the tracker.

if (document.cookie.indexOf(disableGa + '=true') > -1) {
    window[disableGa] = true;
    // Remove the tracker
    ga(function () {
        ga('remove', gaProperty);
    });
} else {
    // Create the tracker
    ga('create', gaProperty, 'auto', {
        anonymizeIp: true
    });
    ga('send', 'pageview');
}

因此,当用户到达页面时,我要么实例化创建跟踪器,要么不实例化。我不清楚的是remove属性。

在此之后,页面上有一个按钮,允许用户切换 GA 状态。

该功能与上述功能几乎相同。但我也想允许动态启用谷歌分析的选项。

我正在按照示例处理饼干:

// 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;
}

然后我的想法是为每个用户请求注册/注销跟踪器,但我不确定我是否正确。

// Remove the tracker
ga(function () {
    ga('remove', gaProperty);
});

不确定是否值得一提,但我正在 Angular 应用程序中实现这一点。

另外,我有条件地创建和删除的原因是因为我记得读到在发出ga('create')之前必须设置全局属性window.ga-disable-UA-XXXX-Y = true

为了调试,我使用的是 Google 的标签助手,它在切换 GA 时报告重复使用跟踪 ID。https://jsfiddle.net/vLyeszfg/18/

正如您可能看到的,我成功地以编程方式启用了谷歌分析,但删除是问题所在。

我从未使用过 delete,但根据文档,它不需要参数 - 它按名称删除跟踪器实例,而不是给定属性的跟踪器(因此ga('remove')删除默认跟踪器,ga('myCustomTracker.remove')删除命名跟踪器实例"myCustomTracker"等。

但是,我不确定为什么您会费心启用选择退出和删除跟踪器(当没有跟踪器实例时,选择退出毫无意义)。