Fork Me
webcloud / log / Protecting Your Google Analytics Data Integrity

When people see something they want, they copy the entire page source: including your analytics code. If you have something like code examples/tutorials on your website you get this A LOT.

It's a problem because you see stats on your analytics account from somebody elses website. Google doesn't verify the integrity of the data, you can in other words sabotage peoples stats if you are evil.

Development

There's another instance when you don't want to be tracking statistics for your website, when you are developing it.

A solution

No, you won't be able to stop people copying your code. Instead make sure you track only for the hostname on your website.

if(/yourdomain\.com$/.test(window.location.hostname) {
    // Google Analytics code goes here
}

This will work on both yourdomain.com, www.yourdomain.com, and www.subdomain.yourdomain.com. If you're using the same tracking code for several website, this won't work.

Again: This isn't a perfect solution, but it'll keep development and copy/paste people stats out of your Analytics Data.