ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

How to set the Google Analytics cookie only after another consent cookie is set and "true"

2022-07-19 18:03:25  阅读:274  来源: 互联网

标签:function set gtag consent js Analytics cookie


How to set the Google Analytics cookie only after another consent cookie is set and "true"?

 

回答1

The way you were doing it is Opt-out. The GA cookie is always set, as soon as the client requests the gtag.js. This however doesn't comply with GDPR. What you should look into is Opt-in, so that no GA cookie is set without consenting.

The general idea is to async load the gtag.js once the client has consented. For full functionality of gtag functions you have to load the gtag.js on every page-load if the client already consented. Best practice to do this is with a cookieconsent cookie set on consent. There's a widely used js library for this, which generates a popup and sets the consent-cookie for you.

Reference:
https://www.osano.com/cookieconsent/documentation/javascript-api/
You can generate code for the layout of your cookie banner by clicking Start Coding here: https://www.osano.com/cookieconsent/download/ https://github.com/osano/cookieconsent/blob/dev/examples/example-7-javascript-api.html

Following code has to be implemented on every page in the <head> section:

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

Note:
Make sure that the gtag.js is loaded on every page-load once the consent-cookie was set to allow. Use event_callback to see if a gtag event was sent. You can use the gtag function without checking for the consent-cookie. If gtag.js is not present it just adds elements to the window.dataLayer without any functionality. To avoid errors, the function gtag() has to be declared in global scope and before use.

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

You don't have to send an extra pageview event, unless you want to manually specify the path. setCookies() already sends the current document path along with the config

 

回答2

Use gtag's consent config options. Currently, the following can be put before any data measurement commands (config or event) are run in the header:

gtag('consent', 'default', {
  'ad_storage': 'denied',
  'analytics_storage': 'denied'
});

Then run this once the user has approved or if a consent cookie is present:

gtag('consent', 'update', {
  'ad_storage': 'granted',
  'analytics_storage': 'granted'
});

If you use Facebook Pixel, it works in a similar way. E.g. fbq('consent', 'revoke'); then fbq('consent', 'grant').

 

标签:function,set,gtag,consent,js,Analytics,cookie
来源: https://www.cnblogs.com/chucklu/p/16495120.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有