Woidfeeee
Woidfeeee

Reputation: 41

Google Analytics code for tracking 2 domains for one single page

I have a website which is linked to two different domains. In other words I have two domains which point to the same index.html. For analysing the traffic I created an Analytics Account with two properties. Now I would need help with the Javascript. That's what I did so far:

<script>
   (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
   function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
   e=o.createElement(i);r=o.getElementsByTagName(i)[0];
   e.src='//www.google-analytics.com/analytics.js';
   r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
   ga('create','UA-XXXXXXX-1','auto', {'allowLinker': true});
   ga('require', 'linker');
   ga('linker:autoLink', ['myseconddomain.at'] );
   ga('send','pageview');
</script>

Analytics created a second UA-Code but actually I don't use it so far. It also tells me that Tracking for the second property is not installed.

I don't know if this is the right approach. Anyone an idea how to handle this problem? Thx in advance!

Upvotes: 1

Views: 90

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

One way would be to set the tracking id depending on the hosting, which can be retrieved via the javascript location object, specifically document.location.hostname:

<script>

   if(document.location.hostname == "domainB.com") {
      var UAID = "UA-XXXXXXX-2"
    } else { // default case
      var UAID = "UA-XXXXXXX-1"
   }

   (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
   function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
   e=o.createElement(i);r=o.getElementsByTagName(i)[0];
   e.src='//www.google-analytics.com/analytics.js';
   r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
   ga('create',UAID,'auto');
   ga('send','pageview');
</script>

This is if you insist on two separate properties. If the properties share identical configurations it might be easier to use a single property and create two views each with an include filter for the respective domain.

Upvotes: 2

Related Questions