Grady D
Grady D

Reputation: 2019

Run google analytics on a specific Url

I have multiple sandbox/development environments that all pull from the same code due to refreshes and such. The problem is that I have google analtics included in my footer template part and I am flooded with junk test data when I run reports.

My solution is to write some jquery code that checks the URL and run if the url matches our production url. Is there a better way to do this? If not my code is below,

if (location.href==url) {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-*******-1', 'auto');
  ga('send', 'pageview');
}

where url equals the production url. The problem with this is that I am not sure how to match just the root URL. Currently it will match like this production.com/dummy/url?123 with production.com which is not equal. How can I have it match everything up until the end of the .com?

Upvotes: 0

Views: 53

Answers (3)

BA_Webimax
BA_Webimax

Reputation: 2679

You have a couple of options...

Since you said this is for test purposes, if you are not using IE to do your testing, then you can use the window.location.origin ( http://www.w3schools.com/jsref/prop_loc_origin.asp ) property to quickly check your live vs. development URL.

var locURL = window.location.origin;
var checkURL = 'http://host.domain.tld';

if ( locURL == checkURL )
{
    alert( 'Match!' );
}

If you need full browser support, you'll have to parse the URL. Easiest way I can think of is to split it and reassemble...

URLarray = window.location.href.split( '/' );
prot = URLarray[0];
host = URLarray[2];
locURL = prot + '//' + host;
var checkURL = 'http://host.domain.tld';

if ( locURL == checkURL )
{
    alert( 'Match!' );
}

Upvotes: 0

Academia
Academia

Reputation: 4124

You can use regex matching over location.href like this:

var re = /[^\/]*/; 
var str = 'production.com/dummy/url?123';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
}

to get all characters preceding the /

Hope it's useful!

Upvotes: 0

Nick Blexrud
Nick Blexrud

Reputation: 9603

Why not just create a filter that includes only traffic to hostname equals production.com, and another that looks at staging.com?

enter image description here

Upvotes: 3

Related Questions