195

According to EU Article 5(3) of the E-Privacy Directive (a.k.a 'The Cookie Laws'), web sites that target EU users have to gain opt-in consent from users before they set a cookie.

See ICO Guidance

I am trying to square this with Google Analytics on my web site.

I would imagine that Google Analytics (GA) can do a certain level of analytic data gathering without requiring the use of cookies.

However, I cannot find any info on this (on the Google sites/settings panels) about how to relay information about the 'state of consent' back to Google during a page request. So, my only option seems to be that I should not embed Google tag code at all if the user has not explicitly given consent. Which seems a bit drastic.

Letting my serverside script set a hasConsentedToCookies=FALSE flag in the JavaScript tags would allow me to instruct Google's services to run in a gracefully degraded fashion.

Is there a setting on Google Analytics to suppress use of cookies for users that have not yet given consent?

If so, where can I find info on this?

the
  • 21,007
  • 11
  • 68
  • 101
JW.
  • 4,821
  • 5
  • 43
  • 60
  • 2
    Update: This question used to ask about both Adsense and Analytics, But since the answer for each might be differ, I have extracted the ['Google Adsense' aspect](http://stackoverflow.com/q/10670940/205814) out of this question to let each one be more cohesive. – JW. May 20 '12 at 05:14
  • Some intersting discussion on http://news.ycombinator.com/item?id=4032633 – Eduardo May 28 '12 at 11:21
  • Just in case you don not know this: Have you heard about piwik? (http://piwik.org/) – TheHippo May 29 '12 at 05:18
  • Good and interresting question! – Rob May 29 '12 at 09:20
  • Google says that you can disable cookies however it does not seem to work or I'm doing something wrong. Link: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains?hl=en#disableCookies –  Jun 18 '13 at 08:08
  • Just as a side note, piwik (mentioned in a comment above) is now called matomo.org. It is a cookie-free, cost-free, analytics alternative, in case somebody is interested... – J0ANMM Jun 04 '20 at 19:26

15 Answers15

159

EDIT (2019): The below answer predates GDPR and likely requires revision.

Google Analytics has a new set of APIs to assist with compliance with a cookie opt-out. Here's the documentation, and here's their help docs.

There has been some ambiguity as to whether the EU Cookie Regulations (as implemented in member countries) require that passive web analytics tracking requires opt-in mechanisms for compliance. If you're concerned one way or another, consult an attorney. Google is empowering you to make the decision as to how you want to proceed.

They'll leave implementation details to you, but, the idea is, once you've determined whether or not to track the user in Google Analytics, if the answer is to not track, you'd set the following property to true before Google Analytics runs:

window['ga-disable-UA-XXXXXX-Y'] = true;

Where UA-XXXXXX-Y is your account ID in Google Analytics

As the other posters have noted, Google Analytics relies on cookies. So, you're not able to do any kind of tracking without cookies. If you've determined that someone is not to be cookied for tracking, you'll need to implement something like this:

if(doNotCookie()){
   window['ga-disable-UA-XXXXXX-Y'] = true;
}

Opt In

This does require a little bit of jujitsu for when you first load Google Analytics, since this property will need to be set before Google Analytics runs to prevent tracking from ever happening, which means, for an "opt in to tracking" approach, you'd probably need to implement a mechanism where, on first visit, Google Analytics is automatically disabled in the absence of an opt-in cookie (cookies that determine cookie preferences are explicitly allowed), and then, if an opt-in happens, re-runs Google Analytics. On subsequent pageviews, all would run smoothly.

Could look something like (pseudo-code):

if( hasOptedOut() || hasNotExpressedCookiePreferenceYet() ){ //functions you've defined elsewhere
     window['ga-disable-UA-XXXXXX-Y'] = true;
}
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
  _gaq.push(['_trackPageview']);


  function onOptIn(){ //have this run when/if they opt-in.
      window['ga-disable-UA-XXXXXX-Y'] = false;
      //...snip...
      //set a cookie to express that the user has opted-in to tracking, for future pageviews
      _gaq.push(['_trackPageview']); // now run the pageview that you 'missed'
   }

Opt Out

With this approach, you'd allow the user to opt-out of tracking, which would mean you'd use a cookie to set the ga-disable-UA-XXXXXX-Y' property and a cookie to manage it in the future:

if( hasOptedOut() ){ // function you've defined elsewhere 
     window['ga-disable-UA-XXXXXX-Y'] = true;
}

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
  _gaq.push(['_trackPageview']);
Yahel
  • 37,023
  • 22
  • 103
  • 153
  • 2
    Tiny nitpick on a good answer - if(doNotCookie(){ should be if(doNotCookie()){ – Roee Shenberg May 28 '12 at 18:59
  • 1
    Thanks for the answer. Although I'd wouldn't say 'consult an attorney'. Its probably quicker for a techy to read and understand the guidance than it would take an attorney to learn the nuances of the technicalities. – JW. May 30 '12 at 10:21
  • 2
    Am I to understand that if the user elects NOT to have cookies stored, the solution is to store a cookie with this preference? Or is this cookie not deemed to fall under the EU regulation? – Jonathon Horsman Jun 27 '12 at 17:31
  • 5
    Yes. Most of the regulations I've seen (specifically, UK's and I believe France's) say explicitly that a cookie storing their cookie preference is not a violation of the rules. Since cookies are the only universally-accessible way of storing state in the browser, there's kind of no way around it. – Yahel Jun 27 '12 at 20:45
  • Is using a persistent URL parameter &GA=off across the entire site the only reasonable way to remember that the user hates cookies and tracking features? – Shawn Eary Sep 16 '22 at 16:49
28

You can disable the use of cookies for Google Analytics by specifying the {'storage' : 'none'} option when creating the tracker instance.

See Google's guide on the subject for more details.

bk138
  • 3,033
  • 1
  • 34
  • 28
severin
  • 10,148
  • 1
  • 39
  • 40
  • 2
    The guide says if you disable cookies, you have to implement similar tracking yourself, so this doesn't seem to help. – mpartel Nov 26 '17 at 15:06
  • 10
    @mpartel You do lose some information: returning visitors and multichannel conversions. But if you don't need those, this is still acceptable. – Ali Dec 04 '19 at 12:01
  • Important: it seems that with this, *every pageview* will count as a new session or user. Can someone confirm? – Basj Nov 10 '21 at 13:57
20

As a quick note, the BBC (probably the most popular site in the UK) has taken an interesting approach to complying with cookies - they've displayed a banner to users telling them that cookies are set and provide a couple of links.

This one explains what cookies are. This one lets them manage their cookies, but most interestingly of all they supply a link to Google Analytics to allow users to opt-out of GA in its entirety. So, in summary, the BBC have taken the view that they can tell the user what cookies are set and then provide a link to Google to allow the user to opt out of all GA cookies. For me, that's a lot less hassle than you telling GA to opt-out for an address through JS.

the
  • 21,007
  • 11
  • 68
  • 101
Martin Clarke
  • 5,636
  • 7
  • 38
  • 58
  • 18
    I REALLY wouldn't assume that the BBC's solution is acceptable. In fact, their solution is fundamentally flawed, for at least three reasons: 1) it sets cookies prior to asking whether you are willing to accept them, 2) it must set a cookie in order to save your cookie preferences, and 3) it states that the site will not control 3rd party cookies, which is in direct violation of the spirit if not the letter of the EU directive. I suspect that the Beebs will get smacked over this one, as they're trying to push the boundaries of the law in as many ways as possible while appearing otherwise. – David T. Macknet May 28 '12 at 12:08
  • Have a look at http://blogs.wsj.com/tech-europe/2012/05/25/europe-caught-with-its-hand-in-the-cookie-jar/?mod=WSJBlog for some good discussion. – David T. Macknet May 28 '12 at 12:11
  • Of course, maybe I'm wrong - apparently they've changed the requirements? http://blog.silktide.com/2012/05/dear-ico-this-is-why-web-developers-hate-you/ talks about a change to the requirements, so I don't know any more. Just don't know about these people, and I LIVE here (for now)! – David T. Macknet May 28 '12 at 12:19
  • [The Register](http://www.theregister.co.uk/) have a banner that says by continuing to use their site they assume that your agree to let them use cookies as well as an accept button. – iamichi May 28 '12 at 12:19
  • @David - of course, as with all compliance/regulation problems, you've got to make your own mind up on what is acceptable. For me, I'd expect that the BBC have put a fair amount of thought into this, and I'd expect they've come to the view that their solution is compliant. It'll be interesting to see if the ICO agree with them! – Martin Clarke May 28 '12 at 13:18
  • 6
    @MartinClarke - Well ... actually, I'm not so certain that I'd follow the lead of a media company, in particular because I'd expect that BBC holds a special position within the UK and would likely be told to shape up, rather than being slapped with a fine. I think it's more a question of risk - BBC doesn't have much at risk, as a publicly-funded body, whereas a commercial site might have. – David T. Macknet May 29 '12 at 09:07
19

I often never ask users to opt out for google analytics, that is because i never set cookies and i never save their ip (and other personal data).

(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', 'UA-98765432-1', 'www.example.com', {
  'anonymizeIp': true
  , 'storage': 'none'
  , 'clientId': window.localStorage.getItem('ga_clientId')
});
ga(function(tracker) {
  window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
});
ga('send', 'pageview');

Also check out this code at Convert Google Analytics cookies to Local/Session Storage

This script will not set any cookies, but still track via google analytics. This will actually have the same effect on privacy as using cookies, because google still records the users IP-address.

That is where the anonymizeIp switch comes in. This tells google to only save an anonymized version of the IP-address. An anonymized IP-address is not considered personal data, so the users privacy will be respected.

AFAIK cookie law is all about privacy and does allow website to track their usage. I am not a lawyer or anything but in my opinion this script complies to the EU cookie law.

Check out this plunk to see it in action: http://plnkr.co/MwH6xwGK00u3CFOTzepK

Community
  • 1
  • 1
Elmer
  • 9,147
  • 2
  • 48
  • 38
  • hello, this is not always a safe approach: [here](https://github.com/h5bp/html5-boilerplate/issues/1444#issuecomment-57235840) are the reasons. – caesarsol Jun 09 '15 at 12:49
  • That is what the `'anonymizeIp': true` option is for, this will not store an ip-address. I like to use localstorage over cookies for a couple of reasons that have nothing to do with the cookie law. – Elmer Oct 17 '15 at 14:32
  • 10
    No, this does not comply at all : - anonymizeIp is misleading and still keeps too much information according to EU laws - LocalStorage is considered as "Cookie" by EU laws So this piece of code gives you less information in GA and still does not comply with the law. – Flunch Mar 24 '17 at 10:09
  • 1
    The "EU cookie law" is actually a directive, so it depends on the specific laws of the UE members. For example, the Italian privacy authority explicitly stated that for the Italian law user consent is not required if you anonymize the IP address and disable sharing of data with other services on the Google Analytics console. – mcont Apr 27 '18 at 13:32
  • I really like this solution and in response of the EU law I am pretty sure that unless in cooperation with the ISP and the government, no combination of these data can identify a person. The clientId stored in LocalStorage is merely a random string as described in Google's docs. – Wang Yu May 02 '18 at 09:10
  • 6
    @Flunch *"anonymizeIp is misleading and still keeps too much information according to EU laws"* Please provide references. Why isn't it acceptable, and when would it be OK? What is *"too much information"*? – Ali Dec 04 '19 at 12:03
10

Latest Google Analytics (gtag.js) has a "Consent mode" just for that (still in beta):

https://developers.google.com/gtagjs/devguide/consent

It looks like this:

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

Then you can update these settings at a later time in the case the user consents.

Francesc Rosas
  • 5,915
  • 2
  • 30
  • 16
  • It is worth mentioning that it must be called before any other commands that send measurement data, such as config or event. – Artur INTECH May 29 '21 at 15:22
  • I've just recently started working with Consent Mode, first thing that I saw is that GA still creates a cookie named _gali from time to time, even when no consent was given. Apart from that, it seems to work just fine. Still, this is a deal-breaker as long as you have to be GDPR compliant. – tomcat Jan 03 '23 at 13:16
3

You can disable google analytics cookies by adding this code at the top of google analytics code (before line: var _gaq = _gaq || [];):

ga('create', 'UA-XXXXXX-XX', {'storage': 'none'});
ga(function(tracker) {
  var clientId = tracker.get('clientId');
});

However some features of google analytics (for example real time stats) do not work properly after this modification. More about google analytics cookies: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains?hl=en#disableCookies

noname
  • 31
  • 1
  • what would the `var clientId = ...` code do? As far as I know it defines a local variable inside the function, isn't it useless? – caesarsol Jun 04 '15 at 12:59
  • i guess that's only an example, you should use `clientId` inside the function as it is done on http://stackoverflow.com/questions/4502128/convert-google-analytics-cookies-to-local-session-storage/19207035#19207035 – caesarsol Jun 04 '15 at 14:24
2

I was facing the same problem.

Eventually, I got a solution in the line of Elmer's reply but playing safe regarding IPs, that is without using localStorage

// Create a fake ID instead of storing anything locally
function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

...
ga('create', 'UA-XXXXXX-Y', {
        'storage': 'none',
        'clientId': guidGenerator()
});

(-) Every page visited will count as a new visitor in Google Analytics, so I am losing quite a lot of functionalities there.

(+) But I can live with it and I believe I am safe regarding data privacy legislations.

Any feedback or improvement suggestion is more than welcome.

J0ANMM
  • 7,849
  • 10
  • 56
  • 90
1

EDIT: There is a Google Analytics setting for this with the Asynchronous GA snippet.

There isn't a Google Analytics setting for this, as you're suggesting, you would need to conditionally exclude the script for those that have not consented if you want to use the Google Analytics Javascript tracking script.

There are some solutions out there already that can be helpful instead of rolling your own. Javascript: http://cookies.dev.wolf-software.com/demo/index.htm

Here is a solution that allows using Google Analytics basic features without cookies, by doing the tracking server side, this example is in PHP: http://techpad.co.uk/content.php?sid=205

Alex Taylor
  • 1,823
  • 1
  • 13
  • 26
1

Common way to handle this so far is the method used by wolf-software's jquery plugin whereby it prevents the script from running until the user opts in. The ICO updated their guidelines last week, however, to say that it is acceptable to rely on 'implied consent' of the sort used on the BBC site. While I don't really think that's within the spirit of the law, it's what's deemed acceptable by those enforcing it. Given that most of the EU has yet to implement the directive, I'd say it's highly likely they'll follow the UK's lead.

There's an interesting article about the UK updates here:

http://www.redant.com/articles/eu-cookie-law-update-ico-adopts-softly-softly-approach/

Chris Disley
  • 1,286
  • 17
  • 30
1

For a less intrusive UX solution you can set implied consent for google analytical cookies by placing a link to: cookiestatement.eu (no javascript, no popups, no ads)

Matt Clegg
  • 584
  • 1
  • 4
  • 16
1

Sorry for being late to answer but I was looking for the same thing recently until I found out a way myself. It may not be the right way to do it but it works. (only works on site in question does not opt-out of GA completely). I have tested for a few days to make sure.

The way I have managed to do it is using a PHP cookie. First start off with adding the analyticstracking.php include...

<?php include_once('analyticstracking.php'); ?>

and in analyticstracking.php add the following...

<?php
if($_COOKIE['consent_cookie']=="Y"){
?>

<script type="text/javascript">
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-********-*']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript';     ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' :      'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];      s.parentNode.insertBefore(ga, s);
  })();
</script>

<?php   
}
else{
//do nothing
}
?>

Before the user has consented to cookies Google Analytics won't work and once they have, the 'consent_cookie' will be saved and will allow GA to work but if the 'google' cookie is destroyed it will stop GA from working (Obviously).

Like I said it may not be the right way but I have tried and tested and it does. Hope this helps somebody.

Pezmo
  • 11
  • 2
1

Update 2022: Its not about Cookies anymore. Now you need a consent even for loading google fonts from outside the EU. This is because doing so the users IP (very private Information haha) will be send to the USA. Im not a lawyer but this affects Adsense and Analytics as well. Here you will find a solution how to load Adsense and Analytics only if consent is given: https://stackoverflow.com/questions/70967060/loading-google-adsense-analytics-and-youtube-only-when-consent-is-given

Simply call setTimeout("analyticsladen()", 1); when consent is given:

The new Google Analytics 4 Code is:

 <script>
 window.dataLayer = window.dataLayer || [];
 function gtag(){dataLayer.push(arguments);}
 gtag('js', new Date());

 gtag('config', 'G-####');
 </script>


 <script type="text/javascript">
 function analyticsladen() {
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'https://www.googletagmanager.com/gtag/js?id=G-####';
 document.body.appendChild(script);
 }
 //setTimeout("analyticsladen()", 1);
 </script>

Or you can use the old Google Universal Analytics Code. It will only work till June 2023 (says google):

 <script type="text/javascript">
 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-####-#']);
 _gaq.push (['_gat._anonymizeIp']);
 _gaq.push(['_trackPageview']);

 var analyticsladen = function(){
 var ga = document.createElement('script');
   ga.type = 'text/javascript';
   ga.async = true;
   ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

   var s = document.getElementsByTagName('script')[0];
   s.parentNode.insertBefore(ga, s);
   }

 </script>

Funfact: Google ranks my page 4 steps higher scince im not using analytics at all anymore :D

human
  • 467
  • 4
  • 6
0

There's a few steps to do in order to make GA work only after user accepts the cookie usage.

Disable cookies

   <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-Y"></script>
-- <script>
-- window.dataLayer = window.dataLayer || [];
-- function gtag(){dataLayer.push(arguments);}
-- gtag('js', new Date());
-- gtag('config', 'UA-XXXXXX-Y');
-- </script>

At the point where GA is implemented, this needs to be updated by just importing the gtag.js script and removing the GA initialisation.

Enable GTag when user accepts cookies

GTag Opt In is a tool that enable and disable GA when user accepts/rejects cookies.

<script src="https://www.npmcdn.com/gtag-opt-in@2.0.0/dist/index.js"></script>
<script>
  GTagOptIn.register('UA-XXXXXX-Y');

  ...
  // On user opt in
  GTagOptIn.optIn();
  // On user opt out
  GTagOptIn.optOut();
  ...
</script>

Library is loaded. GA tracking ID is registered. Later the optIn and optOut functions can bind to user actions' accept/reject.

You can read more about it on How To Implement Google Analytics With Opt In.

Lucio
  • 4,753
  • 3
  • 48
  • 77
0

You can use something like Legal Monster - to block cookies if user didn't give consent for analytical cookies.

legal.js currently supports blocking (and enabling) of analytics and marketing cookies; more categories will be available in the future.

Here is more detailed guide on blocking cookies.

-4

GA does not work without cookies, it needs it to 'identify s' the visitor if he/she visited your site before. So there is no setting in GA for this, GA just doesn't records the visitor if it cant create a cookie.

If the user is from the EU and has not opt-in then you should exclude the google-analytics script I think.

Scriptor
  • 1,125
  • 1
  • 6
  • 13