Hoppa till huvudinnehåll

Disable Google Analytics until consent has been given



This blogpost describes how to create a solution with GTM (Google Tag Manager) whereby  Google Analytics may be blocked until one collects consent from the user. 

First of all this solution is based on the assumption that you already have a consent solution in place that stores a cookie after consent is given and that you are using GTM to track your site.

1 Create a Custom Tag "Disable GA until consent is given"

We will use a built in function in GA that blocks all tracking

Add the following code and exchange UA-XXXXXXXX-X to you Analytics id and YOURCOOKIENAME to match the cookie you use to store consent:

//Check if consent cookie is set
if( document.cookie.indexOf('YOURCOOKIENAME=') == -1) {
  //If not, then disable tracking (default)
  window['ga-disable-UA-XXXXXXXX-X'] = true;
else  {  
  //Enable tracking
  window['ga-disable-UA-XXXXXXXX-X'] = false;

2 Customise you Google Analytics tracking tag 

Add tag sequencing to your Analytics tag, so that you always force the blocking code to execute before your GA tracking is executed like this:

Add Tag Sequencing to GTM

3 (Optional) add logic to send a page view for the current page after getting consent.

Since this logic means you might lose a lot of data, we can at least make sure that we send a page view for the current page to GA. This is done by adding another custom tag just containing the enabling code.

Add a custom tag "Enable tracking"

  //Enable tracking
  window['ga-disable-UA-XXXXXXXX-X'] = false;

Add a a trigger when user clicks on consent that triggers the custom tag above.

Cookie approve trigger in GTM

Finally, add a new Google Analytics Pageview (I copied the original one)

This tag is also triggered by the cookie consent trigger above. The reason why I add a new Google Analytics tag is that there is usually a delay before the cookie is set and that means that our logic for the standard page view tag will never fire:- since that will check if the cookie exists or not. I realise that you could implement some more logic to avoid having another Page view tag but I thought this was pretty straight forward.

To summarise, this is what you need (+ adding the tag sequencing to your pageview tag)

GTM disable GA until consent is given

Final words

This will only work based if you don't execute any other Analytics tracking before your page view tag is executed (this is the default case). But make sure to validate in GA (live view that page requests are not sent, until you have obtained consent.

Vi hjälper dig nå resultat. Kontakta oss Ring direkt på 08-20 90 04.

Lär dig grunderna i Google Analytics

Jag har handplockat 5 filmer för dig som nybörjare på Google Analytics så att du snabbt och enkelt skall kunna lära dig grun…

Google Analytics Ordlista - Espresso Talk

Detta är ett sammandrag av en dragning om grundläggande begrepp i Google Analytics och visar hur man kan använda custom vari…