Search code examples
google-analyticsuniversal-analyticsanalytics.js

Multiple accounts on Universal Analytics


I got a website builder app where users can create their own sites.

Each customer points his domain to the app's ip which has its own UA code to collect data and show page views statistics in the back office. In addition, if customer got his own Google Analytics account he may indicate it and start tracking data.

The current frontend ga.js code looks like this:

<script type="text/javascript">
    var _gaq = _gaq || [];

    /* app UA code */
    _gaq.push(['x._setAccount', 'UA-XXXXXXX']);
    _gaq.push(['x._setDomainName', 'customersdomain.com']);
    _gaq.push(['x._setAllowLinker', true]);
    _gaq.push(['x._trackPageview']);

    /* customer's UA code */
    _gaq.push(['_setAccount', 'UA-YYYYYY']);
    _gaq.push(['_trackPageview']);

    (function () {
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    })();
</script>

Now I need to migrate to Universal Analytics but I am not sure what code should I use. I've done plenty of searches but I am still doubting. Would the following code work?

<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');

    ga('create', 'UA-XXXXXXX', 'customersdomain.com');
    ga('create', 'UA-YYYYYYY', 'customersdomain.com');
    ga('send', 'pageview');

</script>

Solution

  • You need a named tracker. You can set this up in the configuration object that can be passed as the third parameter instead of a cookie domain (in that case the cookieDomain setting goes into the configuration object). Plus you need two send pageview calls, one for each tracker.

    <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');
    
        ga('create', 'UA-XXXXXXX', {
           'name' : 'mycustomtracker',
          'cookieDomain' : 'customersdomain.com'
        });
        ga('create', 'UA-YYYYYYY', 'customersdomain.com');
        ga('mycustomtracker.send', 'pageview');
        ga('send', 'pageview');
    
    </script>