When you visit your own blog or website, Google Analytics still tracks it as a view, which kind of corrupt your stats a little. If you want to check your site and keep the analytics data clean and legitimate, you must somehow exclude yourself from all the visits on all the pages.
Two options are usually offered:
- Chrome extension to block analytics tracking.
- Google analytics exclude filter to ignore visits from your IP address(es).
The problem with the first solution is that it won’t work on non-chrome browsers and other devices. The second one only works so far as your IP address remains static (for most users the IP is dynamic and changes frequently).
This brings us to a programmatic workaround. Let’s take it in steps:
1. Add Google Analytics Code Dynamically
Firstly, this is the script Google Analytics share for tracking (with a unique tracking code), and ask us to place in the head tag of our website:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-114947177-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-114947177-1');
</script>
The trick is to add this code dynamically. The above code can be replaced with:
<script>
var head = document.getElementsByTagName("head")[0];
var adScript = document.createElement("script");
adScript.type = "text/javascript";
adScript.src = "https://www.googletagmanager.com/gtag/js?id=UA-114947177-1";
adScript.async = true;
head.appendChild(adScript);
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-114947177-1');
</script>
2. Pass Your Secret Check via Query Params
We need to identify that it’s you who’s visiting the website/blog. If we know that we can omit the inclusion of the analytics script. The easiest way is to pass a query parameter in the address bar, and then check for it before adding the script. Here I’m passing owner=yes
.
https://www.example.com/?owner=yes
(we’re only interested in owner
and don’t really care about the value).
<script>
var urlSearchParams = new URLSearchParams(window.location.search);
var params = Object.fromEntries(urlSearchParams.entries());
if (!params.owner) {
var head = document.getElementsByTagName("head")[0];
var adScript = document.createElement("script");
adScript.type = "text/javascript";
adScript.src = "https://www.googletagmanager.com/gtag/js?id=UA-114947177-1";
adScript.async = true;
head.appendChild(adScript);
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-114947177-1');
}
</script>
With this combination of conditional addition of analytics code and query param ?owner=yes
in the address bar, you won’t be tracked!
3. Make It Permanent With Local Storage
The above approach will work but just for one initial page. As soon as you click another link on your site, the query parameter will be gone and you’ll again be tracked. To get around this we can persist the owner information in localStorage
as follows:
- Check if localStorage on this domain has a key
owner
. - If no, check the query parameter for the same.
- If still no, the Google Analytics script will be added (essentially for all the traffic except yours).
- If the query parameter is found, store it in the localStorage. The analytics script won’t be added and no tracking will happen for this and all subsequent visits of the website, on this page or any other.
<script>
var isOwner = localStorage.getItem("owner");
if (!isOwner) {
var urlSearchParams = new URLSearchParams(window.location.search);
var params = Object.fromEntries(urlSearchParams.entries());
if (params.owner) {
localStorage.setItem("owner", "yes");
isOwner = "yes";
}
}
if (!isOwner) {
var head = document.getElementsByTagName("head")[0];
var adScript = document.createElement("script");
adScript.type = "text/javascript";
adScript.src = "https://www.googletagmanager.com/gtag/js?id=UA-114947177-1";
adScript.async = true;
head.appendChild(adScript);
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-114947177-1');
}
</script>
4. Confirm That It’s Working
To verify:
- Add the
?owner=yes
query parameter in front of your website address and hit enter. Once the page loads, you can verify that it’s persisted by opening the chrome dev tools and checking the localStorage section:
- Visit a couple of other pages.
- Head to the Google Analytics dashboard, and confirm no new visit/user was recorded for the pages you just opened.
- Now open the same website in incognito mode (or after clearing the browser’s localStorage), and reload the page (without query parameter). This visit should show up in the Google Analytics dashboard.
Note: You’ll have to add the query parameter ?owner=yes
once on any new browser you open your site on, and also in case you open it in incognito mode or after clearing up your localStorage.
5. Omit Tracking of Localhost Environment
While working on the localhost environment, you can check the exact origin and verify it’s not localhost before moving on to the ?owner=yes
query parameter check.
This is handy because on localhost you might need to clear your cache often for testing, which will restart analytics tracking for your own visits. Checking localhost acts as a safeguard.
For this, just wrap the above code we have in a if(location.origin !== "http://localhost:1313"){}
block. Port could be any other than 1313
, such as 3000
, 8000
etc. Change it according to yours.
<script>
if(location.origin !== "http://localhost:1313"){
var isOwner = localStorage.getItem("owner");
if(!isOwner){
var urlSearchParams = new URLSearchParams(window.location.search);
var params = Object.fromEntries(urlSearchParams.entries());
if(params.owner){
localStorage.setItem("owner", "yes");
isOwner = "yes";
}
}
if(!isOwner){
var head = document.getElementsByTagName("head")[0];
var adScript = document.createElement("script");
adScript.type = "text/javascript";
adScript.src = "https://www.googletagmanager.com/gtag/js?id=UA-114940188-1";
adScript.async = true;
head.appendChild(adScript);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-114940188-1');
}
}
</script>
See also
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Date Format Validation With Moment JS
- Yup Number Validation: Allow Empty String
- Exactly Same Query Behaving Differently in Mongo Client and Mongoose
- JavaScript Unit Testing JSON Schema Validation
- Reduce JS Size With Constant Strings
- JavaScript SDK