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

时间:2016-03-11 13:14:23

标签: javascript angularjs google-analytics

我已经实施了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状态。

功能与上述功能几乎相同。但我还想允许动态启用Google分析选项。

我按照示例处理cookie:

// 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应用程序中实现了这一点。

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

对于我正在使用Google's Tag Assistant的调试,它会在切换GA时报告重复使用跟踪ID。 https://jsfiddle.net/vLyeszfg/18/

正如您可能看到的那样,我已成功以编程方式启用Google分析,但删除操作仍然存在问题。

1 个答案:

答案 0 :(得分:1)

我从未使用过删除但according to the docs它不带参数 - 它按名称删除跟踪器实例,而不是给定属性的跟踪器(因此ga('remove')删除默认跟踪器{{ 1}}删除命名的跟踪器实例" myCustomTracker"等。

我不确定为什么你会打扰启用退出并删除跟踪器(当没有跟踪器实例时,选择退出是没有意义的。)

相关问题