Prevent People Messing Up Your Goolge Analytics

After running coding sites for a couple years there is one little problem that really annoys me, so when I set up #! code I resolved to fix it. The issue arises when you use some JavaScript based analytics software that allows multiple domains to be used, like Google Analytics. There is nothing wrong with analytics software that allows this, and it is potentially useful for tracking all manner of things. However, some web masters might not be that good at running sites and will lift code from your site (analytics and all) in order to implement a single widget on their site. What this means is that when a user lands on one of their pages it will register as a hit on your site.

This sort of problem might be quite hard to spot as all you will notice is that people start finding your sites for strange keywords, or pages that you know are not there seem to be appearing in the visited pages list. I once had a site that appeared to get over 1,000 visits per day for the keyword "corvette", which clearly wasn't the case!

So how do you stop this sort of thing? You can just detect the current URL that the user is looking at and see if it contains your domain name. If it does then you can run the code needed to register a hit with the analytics software.

The code below is an example of this in action, which I use on #! code. This also pops up an alert if the URL does not contain your chosen URL. The idea behind this code is not to cripple the site but to force the web master to look at what he is doing a little more carefully and maybe learn one or two things about JavaScript along the way.

<script type="text/javascript"> 
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "' type='text/javascript'%3E%3C/script%3E"));
<script type="text/javascript"> 
try {
    if ( document.location.href.match(/http:\/\/www\.YOUDOMAIN\.com/) != '') {
        alert('I got this code from!');
    } else {
        var pageTracker = _gat._getTracker("UA-YOUR-ID");
} catch(err) {}

I have always said that the best thing a bout the Internet is that anyone can do it, but the worst thing about the Internet is that anyone can do it. There are lots of coding blogs out there that use analytics so I present this code here to help out anyone with the same issue.

Add new comment

The content of this field is kept private and will not be shown publicly.
7 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.