Il Blog di Lorenzo Vainigli

Disable Google Analytics only for site’s administrators

28 July 2019
Programming Web
1 minute    12

Questo articolo è disponibile in italiano

Services used to track visitors to your site, such as Google Analytics, are essential tools to get an idea of the performance of your web pages.

The problem that arises is that administrators, content creators or any other profile that manages the content of a site are among the most active users. In the long run, this activity, which Analytics catalogues as “visitor”, without distinguishing between users and administrators, falsifies the numbers of real users, i.e. those who have no interest in the growth or decrease in numbers of a site.

This is very important, especially if the numbers of visitors will be the basis for the choice of marketing strategies.

How to do that?

Using cookies

To track visitors Analytics uses a short Javascript code like this one, included on every single page of the site that each visitor’s browser runs:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-X');

Quite simply, we can define a cookie to be set in the administrator’s browser (for example no-tracking) and, with a conditional command, tell the code to execute the previous instructions only if the cookie is not present. The value of the cookie is therefore not relevant.

// indexOf(str) returns -1 if there is no occurrence of string str,
// the index of the first occurrence of str otherwise
if (document.cookie.indexOf("no-tracking") === -1){
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXXX-X');

The cookie can also be set manually in the administrator’s browser.

Once this operation has been carried out, Google Analytics will only track the real users who visit the site, making the collected data much more reliable.

Lorenzo Vainigli

Passionate about computers, technology and information technology since I was a child. I have a bachelor's degree in Computer Science from the University of Bologna and I am now studying for a master's degree. Often I like to put my knowledge into practice by creating something new.

© 2020