Respecting visitor's privacy in web analytics

I believe privacy is an important concern and as a web developer or software engineer, you should respect your end-user's privacy. Here is the way I added web analytics to my home page keeping visitor's privacy in mind.

Most browsers have a flag called doNotTrack, which can be enabled by going into the settings[1]. By moving web analytics tracking code to a simple if condition, you can respect this flag.

All web analytics programs provide you a javascript snippet which you need to add to the footer of your webpage. When you add that to your website, wrap it in an if condition like following.

<script>
  // respect user's privacy
  if (navigator.doNotTrack != "yes" && navigator.doNotTrack != "1" && navigator.msDoNotTrack != "1") {
    // paste analytics code here
  }
</script>

for example, Google Analytics tracking code will look similiar to this.

<script>
  // respect user's privacy
  if (navigator.doNotTrack != "yes" && navigator.doNotTrack != "1" && navigator.msDoNotTrack != "1") {
    (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-xxxxxx-xx', 'auto');
    ga('send', 'pageview');
  }
</script>

In this way, a network request to google analytics will happen only if doNotTrack flag is not set by the user.


  1. https://www.eff.org/deeplinks/2012/06/how-turn-do-not-track-your-browser ↩︎