Prevent People Messing Up Your Goolge Analytics

3rd August 2009

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.

  1.  
  2. var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  3. document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  4.  
  5. try {
  6. if ( document.location.href.match(/http:\/\/www\.YOUDOMAIN\.com/) != 'http://www.hashbangcode.com') {
  7. alert('I got this code from www.YOUDOMAIN.com!');
  8. } else {
  9. var pageTracker = _gat._getTracker("UA-YOUR-ID");
  10. pageTracker._trackPageview();
  11. }
  12. } 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.