Google Analytics默认选择退出(可选择加入)

时间:2018-05-10 17:58:52

标签: javascript jquery cookies google-analytics

我在下面有以下代码 - 但我很难找到一种方法,默认情况下禁用它,只有在用户选择进入时才会运行(并记住它当前的情况)。另外我想知道是否可以在没有location.reload(true)的情况下做到这一点 - 还有什么进一步的想法吗?

<div id="google_analytics"></div>

<script>

    var gaProperty = 'UA-XXXXXXXX-X';
    var disableStr = 'ga-disable-' + gaProperty;
    if (document.cookie.indexOf(disableStr + '=true') > -1) {
        window[disableStr] = true;
        console.log('GA is disabled');
    }
    // Opt-out function
    function gaOptout() {
        document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
        window[disableStr] = true;
        location.reload(true);
        console.log('GA is disabled');
    }
    // Opt-in function
    function gaOptin() {
        document.cookie = disableStr + '=false; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        window[disableStr] = false;
        location.reload(true);
        console.log('GA is active');
    }

    if (window[disableStr] == true) {
        document.getElementById("google_analytics").innerHTML = 'You are opt-out from Google Analytics. <a href="javascript:gaOptin()">Opt-in</a>';}
    else {
        document.getElementById("google_analytics").innerHTML = 'This page is using <a href="http://analytics.google.com/">Google Analytics</a>. <a href="javascript:gaOptout()">Opt-out</a>';
    }

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', gaProperty, 'auto');
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');

</script>

0 个答案:

没有答案