We use Webtrends at work to track usage of our websites.
We use the on demand version which relies on embedding a JavaScript tag onto the page. Recently, we’ve moved to using 1st party cookies (cookies set by the site) instead of 3rd party cookies (cookies set externally by webtrends). These are set in the JavaScript tag and are hard coded to the site, a real pain if you happen to move domain names as you need to code them up specifically each time. We got caught out recently by using a tag with the wrong domain name set in it, meaning we were unable to track the page impressions. We needed a solution…
As the tag is being set in JavaScript, we can use JavaScript to set the domain dynamically. Not all our sites are served dynamically so using JavaScript should mean it would work for anyone using this tag.
Here’s the offending bit of code…
// Code section for Set the First-Party Cookie domain
var gFpcDom=".kerrang.com";
This works for anything served from a Kerrang.com domain. However, what if we want to use a different domain for some reason?
We’ll JavaScript has a property in the document
object called domain
, we can use this at runtime to find out the full domain name the page was served from.
However, we don’t need the full domain name, just parent domain. For example, www.kerrang.com should become kerrang.com.
We can fix this by using several approaches, but the easiest is the split, splice, join method.
Firstly we split the domain into it’s components by splitting on the periods.
document.domain.split('.');
This gives us the array (“www”,”kerrang”,”com”).
Secondly we splice this to remove the first element.
document.domain.split('.').splice(1.3);
This is saying to take 3 elements after the 1st element in the array. This should cover us if we want to use something like kerrang.co.uk. So after running this we need to should have an array looking like this, (“kerrang”,”com”).
Finally we join this back together again, making sure a period is between each joined element.
document.domain.split('.').splice(1,3).join('.');
Running this should give us kerrang.com, which is acceptable to use in the Webtrends tag.
So our final code looks like this…
var gFpcDom = document.domain.split('.').splice(1,3).join('.');