Feb 14, 2023

Google Analytics visitor opt-out Javascript

As we discussed in our post about skipping Google Analytics altogether – we’ve written some JavaScript to make it easy for your visitors to opt-out of GA tracking. This post explains in more detail exactly what the code does and how to install.

Our intent with this code is to offer a useful utility – but it has some downsides that we list below, and will probably need a bit of customization for your use case.

But more importantly, we want to get marketers thinking: Do you really need Google Analytics to run an effective marketing department?

Quick overview of the opt-out code

Google Analytics lets web developers make a simple Javascript call to disable tracking. But Google doesn’t provide an easy way for site visitors to trigger it, so we added that. In addition, as far as we can tell, this value isn’t stored between visits to your site, and perhaps not even between pageviews, so we’ve added functionality to make this selection persistent. Lastly, we’ve added functionality to allow users to turn GA tracking back on if they’d like.

Main functions

The key line of this code is Google’s functionality to turn off tracking:

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

Every other line of the code provides the additional functionality described above. For example, readCookie() and setCookie() are fairly standard cookie functions to save and read whether your users has disable GA tracking. The checkCookie() function uses readCookie() to see if an option for disabling tracking has been set; checkCookie() also manages toggling the link text to switch between opted-in and opted-out states.

Setup

To use this, you can drop the code more or less unchanged into any page on your site; that’s what we’ve done with our blog post. The <a> element will work anywhere you place it, and if you have access to a web developer, they can attach this behavior to a button or some other element, instead.

Caveats and warnings

  • Ideally, you should have this code run before your Google Analytics code runs. If Google Analytics is implemented via Google Tag Manager on your site, the easiest way to do that is to take the code between the <script> tags and add it to a new GTM tag that fires before Google Analytics.
  • Another good reason to use Google Tag Manager: This code needs to run on every page of your site where Google Analytics runs.
  • If you’re subject to the requirements of GDPR or any similar legislation – this code isn’t going to be enough to cover those requirements. We don’t offer legal advice, but there are plenty of Cookie Consent companies out there that offer a full solution to this problem.
  • This code sets its own cookie. The irony isn’t lost on us! It’s just a few letters – optedin or optedout – and we tend to think that simpler cookies, that you control directly, are better. But still.
  • This only works for a single Google Analytics tracker, so if you’re using more than one, you’ll need to modify the code to account for that.

The full code

This short script makes it relatively straightforward to allow your users to disable Google Analytics. We’ll continue to develop this code, but mostly we hope this sparks a conversation for you about whether, and how, you want to continue using Google’s tool. Questions? Feel free to chat with us, or open an issue in the GitHub repo.

<a href="javascript:OptOutModule.init()" id="gaOptOutLink">Opt out of Google Analytics tracking</a>

<script>

var OptOutModule = function(){

  var gaCookieName = '_ga_optout',
  	  gaProperty = 'UA-XXXX-Y',
      domainName = window.location.pathname, //or set to your domain
      cookieDuration = 2000;

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

  function checkCookie() {
	gaOptOutLink = document.querySelector("#gaOptOutLink");
    var i = readCookie(gaCookieName);

	if (i == "optedout") {
	  gaOptOutLink.setAttribute('data-optedin','optedout')
	  gaOptOutLink.innerText = 'Opt in to Google Analytics tracking';
	  window['ga-disable-' + gaProperty] = true;
	  if (gaOptOutLink.getAttribute('optin-inited') == 'yes')
	  {
	  	setCookie(cookieDuration, gaCookieName, 'optedin');
	  }
	}
	else 
	{
	  gaOptOutLink.setAttribute('data-optedin','optedin')
	  gaOptOutLink.innerText = 'Opt out of Google Analytics tracking';		
	  window['ga-disable-' + gaProperty] = false;
	  if (gaOptOutLink.getAttribute('optin-inited') == 'yes')
	  {
	  	setCookie(cookieDuration, gaCookieName, 'optedout');
	  }
	}

  gaOptOutLink.setAttribute('optin-inited','yes');
  }

  function setCookie(days, cName, cValue) {
    var d = new Date();
      d.setTime( d.getTime() + (days * 24 * 60 * 60 * 1000) );
      var expires = "expires="+ d.toUTCString();

      document.cookie = cName + "=" + cValue + ";" + expires + ";path=/;domain=" + domainName;
      console.log(cName + ' cookie set: "' + cValue + '"');
  }

  function init() {
    checkCookie();
  }

  return {
    init: init,
    readCookie: readCookie
  };
}();

OptOutModule.init();

</script>
 Copy
html

We’re *actually* here to help

We’re marketers who love spreadsheets, algorithms, code, and data. And we love helping other marketers with interesting challenges. Tackling the hard stuff together is what we like to do.

We don’t just show you the way—we’re in this with you too.

Background image of a red ball in a hole.