Bright Avocado

Selective cookie serving with GTM

One of the most common problems I face when designing analytical setups is how to get Google Tag Manager (or short GTM) to serve different instances of Google Analytics, remarketing codes or other analytical software based on user input.

Basic logic

The basic premise is simple: when a user explicitly shows their intent to allow certain features on the website then you can turn them on.

There are different approaches to this but I selected a combination of:

  1. onsite JavaScript code
  2. first party cookies
  3. custom Google Tag Manager variables and tags

You can of course use any other storage options that will enable you to read the user decision in the long run.

Defining the needs of your website

First step in this process is to accurately define which functions your site allows the user to enable or disable. This example will be based on Bright Avocado cookie policy selection (with a few adaptation to the code as some of the things will not be necessary for you). In my case I had three distinct segments that needed to be defined:

  1. Necessary cookies (cannot be disabled due as the website will not function without them)
  2. Analytical cookies and codes – includes Google Analytics and internal analytical systems designed to better understand user decision process.
  3. Third party cookies – help us better optimize our advertising and minimize frequency of ad serving.

You can check the segments on this page https://brightavocado.com/cookie-usage/. Okay first part is solved, time to get down and dirty!

Creating selectors on the website

Due to simplicity I decided to use toggle switches that allow the user to enable or disable said functions on the website.

Here is an example of a toggle switch (in this case it will do absolutely nothing).

Enable/disable selected cookies.

There’s a number of fancy toggles on the web but seeing this is a pretty simplistic and clean site I opted for the most basic look. The whole code is available on w3schools.com. You can adapt that code or go for one of the other ones.

The basic HTML code for the switch is here:

<label class="switch">
  <input id="analyticalCookies" type="checkbox" onclick="crumbs(this.id)" checked="1">
  <span class="slider"></span>
</label>

Each toggle has an ID to differentiate it later on. I also added the on click

I wanted to have all options enabled by default so the basic input code contains checked=”1″ attribute. This tells the CSS to shine bright green until turned off!

Remembering your decision

It is easy to change the toggle from on to off, but how do you keep the website honoring user’s decision after refreshing the page or navigation to a different subpage? I opted for first party cookies which are also easily read by Google Tag Manager with the first party cookie variable.

To get this working I put together five functions that help create, read and erase cookies as well as take care of user interactions. A large part of the code below is by Travis Hoover who published it on GitHub.

function crumbs(clicked_id) {
 	var crumb = document.getElementById(clicked_id).checked;
 	if (crumb) {
 		eraseCookie(clicked_id)
	}
    else {
    	createCookie(clicked_id,1,180);
    }
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
function checkCookie(setID) {
    var checkedCookie = readCookie(setID);
    if (checkedCookie == null) {
        document.getElementById(setID).setAttribute("checked", "1");
    }
}
function readCookie(name) {
	var nameEQ = name + "=";
	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,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
window.onload = function(){
	var analyticalExists = document.getElementById("analyticalCookies");
		if(analyticalExists != null) {
			checkCookie('analyticalCookies');
		}
}

This website is based on WordPress so I created a custom shortcode to ease the deployment of different toggles across the website. If you’re not sure how to create a WordPress shortcode I kindly suggest you visit WordPress Shortcode API as often this comes in really handy.

Acting upon user interaction

So the user told you what they want. What now? Well you have two options:

  1. Continue with hardcoded functions (if you want to completely disable load of GTM until confirmation)
  2. Use GTM variables and tags.

For this tutorial we will use the second option, but you can also develop the first option from the code above.

Using Google Tag Manager to read cookies

GTM enables us to create a first party variable, which can easily read the data stored in that cookie.

All you need to do is to head over to the tag manager, navigate to Variables and click on create new variable.

Then you need to select the 1st party cookie variable as seen below

1st Party cookie variable selector

If you don’t see the highlighted page variable then you need to enable this built in variable.

After successfully adding the 1st Party Cookie variable add the cookieID (this is the value you used for the switch ID) so it knows what to check for.

1st Party Cookie variable setup

All you need to do now is setup the triggers that will power your tags. After a toggles is turned off, it will set a first party cookie. This cookie will contain just a simple number 1.

GTM trigger setup

The logic is, if the trigger detectes a cookie with the correct ane and it includes the number 1 then it will fire.

Due to the way this is set up it will be perfect for exclusions like I did below

GTM tag exlusions

The way this is set up, it will block both analytical codes if the user decides not to accept this segment.

This is however just a simple example, there are a lot more ways to put this to use and advance your Google Tag Manager skills!

Anze Hribar

1 comment

Follow Bright Avocado

Don't be shy, connect with me!

Bright Avocado

Bright delightful and good looking just like your favourite avocado.

Those are the statistics you should see in your analytics, be it for your website or social media!

Tips and tricks

Don't lag behind the best. Join my weekly newsletters!

Sign me up Scotty!