Google Analytics: Track One Website with Two Domains (e.g. dot-com and dot-ca) with Universal Analytics
The Muddling Thru blog has two domain names: muddlingthru.ca and muddlingthru.com. I wanted to setup Google Analytics to track both. Here is the code that did it.
Example
<script>
(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' );
// this must happen before require ga( 'create' , 'UA-XXXXXX-X' , 'auto' , { 'allowLinker' : true });
// this links the two domains ga( 'require' , 'linker' ); ga( 'linker:autoLink' , [ 'muddlingthru.com' , 'muddlingthru.ca' ]);
// this sends the analytics ga( 'send' , 'pageview' );
</script>
Test
- Install the Google Analytics Debugger in Google Chrome.
- Turn it on.
- Open the JavaScript console (Ctrl + Shift + J)
- Reload the page to view possible errors.
See also
https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain#autolink