只有在设置了另一个同意 cookie 并且“true”之后,如何设置 Google Analytics cookie?

flo*_*flo 7 javascript cookies google-analytics reactjs next.js

我正在为我的网站和 react-cookie-consent 库使用 React/Nextjs。它会创建一个弹出窗口,用户可以在其中同意 cookie 策略。如果同意,则设置一个 cookie:值为“true”的 CookieConsent。

此外,我想使用 Google Analytics 来跟踪用户是否同意(单击弹出窗口中的接受)。

但它不起作用:在用户单击弹出窗口之前设置了 Google 分析 cookie _ga 和 G_ENABLED_IDPS。

有趣的是,我只在 Microsoft Edge 浏览器上意识到这一点。在 Chrome 中,这些 cookie 在用户同意之前不会设置。

这是我在 _document.js 中的当前代码:

<Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}            
            gtag('js', new Date());
            
          `}}
          />
          
          <script type="text/javascript" src="/static/blockReactDevTools.js" />
          
          <link href="https://fonts.googleapis.com/css?family=Cabin&display=swap" rel="stylesheet" />

</Head>
Run Code Online (Sandbox Code Playgroud)

我使用互联网上的一些提示进行了尝试,并提出了这个也不起作用的版本:

<Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script 
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />

          <script        
            dangerouslySetInnerHTML={{
                __html: `
              
              var gtagId = '${GA_TRACKING_ID}';

              window['ga-disable-' + gtagId] = true;

              window.dataLayer = window.dataLayer || [];

              function gtag(){dataLayer.push(arguments);}   

              gtag('js', new Date());

              function getCookie(cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for(var i = 0; i < ca.length; i++) {
                  var c = ca[i];
                  while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                  }
                  if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                  }
                }
                return "";
              }

              window.addEventListener("load", function() {
                var isCookieConsentTrue = getCookie("CookieConsent") == 'true';

                if(isCookieConsentTrue){
                    window['ga-disable-' + gtagId] = false;
                    alert("Cookie Consent given!");
                    
                  }  else {
                    alert("Cookie Consent NOT given!");
                    window['ga-disable-' + gtagId] = true;
                  }
              });          
            
            `}}
          />

          <script type="text/javascript" src="/static/blockReactDevTools.js" />

          
          <link href="https://fonts.googleapis.com/css?family=Cabin&display=swap" rel="stylesheet" />

</Head>
Run Code Online (Sandbox Code Playgroud)

我不知道这是 nextjs 特定问题,还是普通愚蠢的问题。

任何人都可以指导我找到可行的解决方案吗?

编辑:我尝试了建议的“通用分析”方法。建议的解决方案使我的辅助函数记录事件和浏览量失败(见下文)。我还需要 gtag 管理器吗?

在此处输入图片说明

wil*_*ire 28

使用 gtag 的同意配置选项。目前,可以在标头中运行任何数据测量命令(config或)之前放置以下内容:event

gtag('consent', 'default', {
  'ad_storage': 'denied',
  'analytics_storage': 'denied'
});
Run Code Online (Sandbox Code Playgroud)

然后在用户批准或存在同意 cookie 后运行此命令:

gtag('consent', 'update', {
  'ad_storage': 'granted',
  'analytics_storage': 'granted'
});
Run Code Online (Sandbox Code Playgroud)

如果您使用 Facebook Pixel,它的工作方式类似。例如fbq('consent', 'revoke');然后fbq('consent', 'grant')

  • 这才是真正的答案。 (7认同)

5an*_*dr0 15

你这样做的方式是选择退出。只要客户端请求 gtag.js,就会始终设置 GA cookie。然而,这不符合 GDPR。您应该研究的是Opt-in,以便未经同意的情况下不会设置任何 GA cookie。

总体思路是在客户同意后异步加载 gtag.js。要获得 gtag 函数的全部功能,如果客户端已经同意,您必须在每次页面加载时加载 gtag.js。执行此操作的最佳做​​法是在同意时设置 cookieconsent cookie。有一个广泛使用的 js 库,它会生成一个弹出窗口并为您设置同意 cookie。

参考:
https : //www.osano.com/cookieconsent/documentation/javascript-api/
您可以通过单击此处开始编码来为您的 cookie 横幅的布局生成代码:https : //www.osano.com/cookieconsent/download / https://github.com/osano/cookieconsent/blob/dev/examples/example-7-javascript-api.html

以下代码必须在该<head>部分的每个页面上实现:

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js" data-cfasync="false"></script>
<script>
var popup;
window.addEventListener('load', function(){
  window.cookieconsent.initialise({
   //set revokeBtn if you don't want to see a tiny pullup bar overlapping your website
   //if revokeBtn is set, make sure to include a link to cookie settings in your footer
   //you can open your banner again with: popup.open();
   //revokeBtn: "<div class='cc-revoke'></div>",
   type: "opt-in",
   theme: "classic",
   palette: {
       popup: {
           background: "#000",
           text: "#fff"
        },
       button: {
           background: "#fd0",
           text: "#000"
        }
    },
    onInitialise: function(status) {
      // request gtag.js on page-load when the client already consented
      if(status == cookieconsent.status.allow) setCookies();
    },
    onStatusChange: function(status) {
      // resquest gtag cookies on a new consent
      if (this.hasConsented()) setCookies();
      else deleteCookies(this.options.cookie.name)
    },
/* enable this to hide the cookie banner outside GDPR regions
    law: {
      regionalLaw: false,
    },
    location: true,
    },
*/
    function (p) {
        popup = p;
  })
});

//it is absolutely crucial to define gtag in the global scope
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {'anonymize_ip': true});

function setCookies() {
    var s = document.createElement('script');
    s.type = "text/javascript"
    s.async = "true";
    s.src = "https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}";
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);

    // you can add facebook-pixel and other cookies here
};

function deleteCookies(cookieconsent_name) {
        var keep = [cookieconsent_name, "DYNSRV"];

        document.cookie.split(';').forEach(function(c) {
            c = c.split('=')[0].trim();
            if (!~keep.indexOf(c))
                document.cookie = c + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/';
        });
};
</script>
Run Code Online (Sandbox Code Playgroud)

注:
请确保gtag.js装在每个页面加载一次同意cookie的设置为允许。使用event_callback,看是否有GTAG事件被发送。您可以使用 gtag 功能而无需检查同意 cookie。如果 gtag.js 不存在,它只会向window.dataLayer没有任何功能的元素添加元素。为避免错误,function gtag()必须在全局范围内并在使用前声明。

// cookie-check is not necessary when gtag is in global scope
//if(popup.hasConsented()) { 
    gtag('event', 'sign_up', {
            'method': 'Google',
            'event_callback': function(){alert('event was sent');}
        });
//}
Run Code Online (Sandbox Code Playgroud)

您不必发送额外的 pageview 事件,除非您想手动指定路径。setCookies()已经将当前文档路径与配置一起发送