Skip to content

Instantly share code, notes, and snippets.

@ChrisButterworth
Created May 24, 2018 10:30
Show Gist options
  • Save ChrisButterworth/ba9066598cae434ad1694e75b7806552 to your computer and use it in GitHub Desktop.
Save ChrisButterworth/ba9066598cae434ad1694e75b7806552 to your computer and use it in GitHub Desktop.
Making Google Analytics behave better

Making GA behave better

Part of GDPR means respecting a users right to privacy (which should be respected anyway regardless of any, this includes the right not to be tracked.

After looking this up I'm surprised at the amount of tracking services in the public domain that completely ignore this; including social media tracking and advertisers. Monsanto (Piwik) is one of the only services I've found to respect do not track requests and even gives you the tools to enable a user to disable tracking.

I've used sessionStorage in the example above but that can be switched out to use localStorage or cookies; if using cookies this needs to be explained within your privacy policy or terms and conditions.

The conditional statement can be used around every tracking function regardless of service.

Enjoy!

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
/* supplied as
function gtag(){dataLayer.push(arguments);}
*/
function gtag(){
if (
navigator.cookieEnabled ||
!(navigator.msDoNotTrack || window.doNotTrack || navigator.doNotTrack) // Cross browser way to detect do not track
/* || sessionStorage.getItem('disabledTracking') */){ // Respect the browser cookie settings and do not track requests
dataLayer.push(arguments);
}
}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX-X');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment