How to use two Google Analytics codes on one page

Table of contents for how to use two Google Analytics codes on one page

  1. Using Google Tag Manager
  2. Using the global site tag (gtag.js)
  3. Using analytics.js

In this article, I am going to talk about how to use two Google Analytics codes on one page.

In some cases, you might want to send data to multiple Google Analytics properties. This is very useful if your website has multiple owners (business function) and each owner would like to track the same website with different approaches.

This can be done in three different ways based on the method of implementation you have used (Analytics.js OR Global Site Tag OR Google Tag Manager).

In order to make it more convenient to read, I have divided this article into three sections based on the methods used.

1. Using Google Tag Manager

If you are using Google Tag Manager as the implementation method, you can follow the steps below to send data to two separate Google Analytics properties.

Creating Google Analytics variables

In order to send data to multiple properties, you need to create separate Google Analytics settings variables as below.

Step-1: Log in to your GTM console and click on ‘Variables’.

Variable Tab

Step-2: Under ‘User-defined variable’, Click on ‘New’.

new variable

As you can see, I already have my one Google Analytics property defined as ‘GA Property 1’. Now let’s create another one.

Step-3: Give a proper name to the new analytics settings variable, let’s say ‘GA Property 2’ and then click on ‘Variable configuration’.

variable name

Step-4: Select ‘Google Analytics Settings’ from the list.

settings variable

Step-5: In the ‘Tracking ID’ input box, paste your analytics tracking ID for the second GA property. Note: You can find the tracking ID in the ‘Admin’ section of Google Analytics under ‘Tracking code’.

tracking code

Step-6: Now click on ‘Save’.

save

You can see there are now two different Google Analytics settings variables and each of them will send data to their separate GA property.

Now, let’s create the tags.

Creating separate Google Analytics tags

You have to create separate GTM tags for each property. You cannot use a single tag to send data to multiple properties.

If you want to send page views to two different properties then you will have to create two pageview tags. The same applies to events as well. For example, if you want to send an event e.g. download event, then you will need to create two event tags, one for each property.

pageview tag
pageview tag setting

The process of creating a tag is similar to normal tag creation. You just need to be careful while selecting the property ID. The best way to do this is by setting up tags for one property first and then copy the tag and rename it after changing the property.

Let’s follow the below steps to copy a tag.

Note: I am assuming that you already have a basic pageview tag for at least one property

Step-1: Go to the ‘Tags’ tab in GTM and identify your first property pageview tag and click on it.

tags tab

Step-2: Now click on the three vertical dots on the right-hand side.

three dots to click

Step-3: A small pop-up will come. Click on ‘Copy’.

copy

The tag will get copied with a name starting with ‘Copy of’ and the original tag name (e.g. Copy of GA Property 1 Pageview).

copy of tag 1

Step-4: Change this name to distinguish it from the earlier one. For example, I am going to name it GA property 2 Pageview. Once done click on ‘Tag configuration’ to edit it.

2nd ta

Step-5: Now click on the drop-down under ‘Google Analytics Settings’.

tag 2 dropdown

Step-6: Now you will see a pop up with a list of created properties and variables. Select the second property to which you want to send data.

property 2

Step-7: Your tag will look like below. Now click on ‘Save’.

save property 2 tag

Congratulations! You have successfully configured tags for sending data to two different properties.

Now, you might be wondering, what about triggers and why is copying tags the best way to configure the second property. Well to answer this you need to understand using GTM triggers.

Using GTM triggers

In above the process we have created separate variables for each Google Analytics property and separate tags as well. But in the case of triggers, they are just conditions for firing the tags, and nothing to do with the Google Analytics property.

This means you can use the same trigger for both tags. Since we are copying the tags, their associated trigger will also get copied. As you can see from the image below, there are two separate tags for Pageview but the trigger is the same.

same trigger

Debugging and validation

Now let’s debug the implementation that we had carried out to send data to two different analytics properties.

Click on the ‘Preview’ button on the GTM console.

preview

It will open up a new window, enter the URL of your website and click on ‘Start’.

preview start

Switch back to the GTM debug window and you can see that the two pageview tags are firing.

two tags firing

You can also see this in the Google Tag Assistance Chrome extension.

tag assistant

So, that is how you can send data to two different analytics properties on one page.

2. Using global site tag (gtag.js)

If you are using the global site tag (gtag.js) for implementation, then you can send data to two different analytics properties with some code modifications to the gta.js library.

Introduction to the global site tag

gtag.js is the new version of analytics implementation. gtag.js is not limited to only Google Analytics but to all Google products, like Google Ads, Campaign Manager, Display & Video 360, Search Ads 360.

You can use gtag.js to send events data to any of these products. Google recommends using the global site tag for all the new Google Analytics accounts.

You just need to add the global snippet on your website, which looks like below.

global site tag
<!-- Global site tag (gtag.js) - Google Analytics -->

<script async src=‘https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-1’></script>

<script>

  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());

 

  gtag('config', 'UA- XXXXXX -1');

</script>

Here, gtag.js uses the ‘config’ command to send data to the Google Analytics property. For example, the following line of code creates a GA property instance.

gtag('config', 'UA-XXXXXX-1');

You can send data to multiple GA properties with minimum configuration changes. Let’s see how it is done.

Configuration of an additional GA property

By default, the global site tag (snippet) sends data to a single analytics property. If you want to add a second property you can achieve this by adding the following command into the main snippet of code.

gtag('config', 'UA-XXXXXX-2');

After adding the command, your code will look like below.

<!-- Global site tag (gtag.js) - Google Analytics -->

<script async src=‘https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-1’></script>

<script>

  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());

  gtag('config', 'UA- XXXXXX -1');

 gtag('config', 'UA- XXXXXX -2');

</script>

Here,  gtag(‘config’, ‘UA- XXXXXX -1’); sends data to the first analytics property and gtag(‘config’, ‘UA- XXXXXX -2’); sends data to the second analytics property.

The overall code sends pageview to both analytics properties, and there is no need to send it using separate commands.

Sending data

In order to send event data, you can use the following command.

gtag('event', 'sign in', {'method': 'Using Password'});

This command will send the ‘sign in’ event to both properties which we defined in the global snippet. You do not need any special command to distinguish the analytics property and then send the event.

If you want to send data to a particular property or group of properties then you need to route it.

Let’s understand more about routing data to groups and properties.

Route data to groups and properties

By default, the global snippet uses the ‘config’ command to handle the routing of events.

If you have configured multiple properties in the global snippet, then event data will be sent to all the properties which you have defined, and no additional configuration is required.

In some cases, if you want to send event data to a particular property only then the global site tag (gtag.js) gives you the ability to send (or route) data to groups of accounts or other Google products.

This is done by using the following command.

gtag('event', 'sign_in', { 'send_to': 'UA- XXXXXX -2' });

The above command will send the ‘sign in’ event only to the second property.

If you are sending data to more than two properties and the business requirement is to send certain information to a set of accounts or Google products and send other pieces of information to another set of accounts or Google products then you can group them using the following command.

gtag('config', 'UA- XXXXXX -1', { 'groups': 'group1' });

gtag('config', 'UA- XXXXXX -2', { 'groups': 'group1' });

gtag('event', 'sign_in', { 'send_to': 'group1' });

This will send data to both analytics properties which are defined under group1.

Let’s take an example, suppose you have three analytics properties configured on one page to which you want to send analytics data. However, there are some events which you only want to send to two properties and not to the third one. You have also classified two of the properties in ‘group1’

In this case, your global snippet will look like below.

<!-- Global site tag (gtag.js) - Google Analytics -->

<script async src=‘https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID’></script>

<script>

  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());

 

  gtag('config', 'UA- XXXXXX -1', { 'groups': 'group1' });

gtag('config', 'UA- XXXXXX -2', { 'groups': 'group1' });

gtag('config', 'UA- XXXXXX -3');

</script>

Now, if you want to send analytics data to all three properties you can use the following command

gtag('event', 'sign in', {'method': 'Using Password'});

If you want to send event data to only two properties classified in ‘group1’

You will use the following command.

gtag('event', 'sign_in', { 'send_to': 'group1' });

This will send data to only ‘UA- XXXXXX -1’ and ‘UA- XXXXXX -2’. It won’t send any data to the third property which is ‘UA- XXXXXX -3’

So this is how you can use the global site tag (gtag.js) to send data to two Google Analytics codes on one page.

3. Using analytics.js

The third method in this article is in conjunction with the article ‘Introduction to Google Analytics Library – analytics.js’ and ‘Introduction to Google Analytics Commands’. 

If you want to send data to multiple web properties from a single web page then you need to understand what trackers are and how they can be created and used. 

Trackers are commonly used for roll-up reporting (reporting of data in aggregate form, from multiple websites/mobile apps) and for implementing cross-domain tracking.

Introduction to trackers in Google Analytics

Tracking object (also known as a tracker) is used to send hit data (pageviews, screenviews, events, transactions, etc) to Google Analytics (GA) web property:

tracking object

Without first creating and using a tracking object, you can not send hit data to a GA property.

Creating a tracking object

Google Analytics ‘create’ command is used to create a tracking object. This command also associates the tracking object with a web property.

For example, the following line of code creates a default tracking object through Google Analytics ‘create’ command and then associate the tracking object with the web property whose id is ‘UA-12345-12’:

ga('create', {'trackingId': 'UA-12345-12'},’auto’);

You can also write this line of code, without using field name, like the one below:

ga(‘create’, ‘UA-12345-12', ‘auto’);

You can see this line of code in your Google Analytics tracking code:

<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-12345-12', ‘auto’);

ga(‘send’, ‘pageview’);

</script>

Following fields are commonly used with tracker(s) and can only be set when using the ‘create’ command:

#1 Tracking id (also known as property id).

You can set the tracking id by using the trackingId field object.

This field object accepts values of type text.

ga('create', {'trackingId': 'UA-12345-21'});

Note(1): I use and recommend field names, to make the code easier to understand and debug.

Note(2): You have to supply a tracking id whenever you use the ‘create’ command method.

#2 Tracker name – it is the name of the tracking object.

The name of the default tracker is ‘t0’.

So following line of code:

ga('send', 'pageview');

is same as:

ga('t0.send', 'pageview');

You set the tracker name only when you are using a non-default tracker.

You can set your own tracker name by setting the ‘name’ field:

ga('create', 'UA-12345-1',{‘name’:’testProperty’});

 The name field accepts values of type text.

#3 Client id – it is a unique random number that is created and assigned by google analytics cookie _ga.

This id is used to uniquely identify a user. 

You can set your own client id by setting the clientId field:

ga('create', 'UA-12345-1', { 'clientId': '8fjfdurehi47-du57ujfdr-379ru307'});

The clientId field accepts values of type text.

Types of trackers

There are two types of tracking objects: default and user-defined tracking objects.

The name of the default tracker is ‘t0’. But we do not refer to the default tracker by this name. To refer to a default tracker, just don’t use any tracker name.

For example:

ga(‘create’, ‘UA-12345-12?, ‘auto’); // default tracker

ga(‘create’, ‘UA-12345-12', {‘name’:’testProperty’},‘auto’); // user defined tracker ‘testProperty’

Note: Google refers to user-defined trackers as named trackers. So named trackers and user-defined trackers are the same things.

Using multiple trackers

Each tracking object can send data to only a single GA property.

So following code won’t work, where we are trying to send hit data to two web properties from a single default 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-12345-12?, ‘auto’);

ga(‘create’, ‘UA-1244524-22', ‘auto’);

ga(‘send’, ‘pageview’);

</script>
single tracker two properties

You need to create two tracking objects if you want to send hit data to two web properties from a single web page:

two google analytics codes on one page

Similarly, if you want to send website usage data to 3 web properties (3 websites/apps) from a single web page then you need to create and use three trackers.

Use the following similar code to send hit data to two web properties from a single web page:

<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-12345-12', ‘auto’); // create default tracking object

ga(‘create’, ‘UA-1244524-22', ‘auto’,{‘name': ‘WebProperty2’}); // create new tracking object named ‘webProperty2’

ga('send', 'pageview'); // send pageview hit to web property 1 via default tracker

ga('WebProperty2.send', 'pageview'); // send pageview hit to web property 2 via  tracker ‘WebProperty2’

</script>

Here ‘WebProperty2’ is the name of the second tracking object.

I selected this name for easy reference. You can name the tracking object whatever you want.

Running Google Analytics commands for specific trackers

Pay special attention to the line of code below which sends pageview data to the web property via the tracking object named ‘WebProperty2’:

ga(‘WebProperty2.send‘, ‘pageview’);

When you are using multiple trackers on a web page, you would need to prefix the Google Analytics command (like ‘send’, ‘require’, ‘linker’ etc) you use with the tracker name. Otherwise, you won’t be able to send hit data to the second web property via the user-defined tracker.

Following are the examples of using Google Analytics commands with the second tracking object:

ga('create', 'UA-1244524-22', 'auto',{'name': 'WebProperty2','allowLinker': true });// allow second web property to pass/accept cookie information

ga('WebProperty2.require', 'linker'); // load the auto link plugin for the second web property.

ga('WebProperty2.linker:autoLink', ['xyz.com'] ); // auto link to xyz website

ga('WebProperty2.send', 'pageview'); // send pageview data to second web property.

ga('WebProperty2.send, 'event', 'videos', 'predators'); // send event data to second web property

Retrieving data stored on a default tracker

To retrieve data stored on a default tracker, we use the get method in a ready callback function

Quick Recap of the Callback function

The callback function is simply a function that is passed as an argument to another function.

The ga() command queue function can accept another function as an argument.

For example:

ga(function_name);

This function executes once the anaytics.js library has fully loaded. 

There can be two types of callback functions in GA depending upon how you use them:

  1. hit callback
  2. ready callback

Hit callback function

Use hit callback function when you want to make sure that a hit is being fired.

This function is called after a hit is processed. No arguments are passed to this function. For example:

ga('send', {

'hitType': 'event',

'eventCategory': 'videos',

'eventAction': 'Play',

'eventLabel': 'chappy',

'eventValue': 100,

'nonInteraction': true,

'hitCallback': function() {alert('hit sent');}

});

Ready callback function

Use ready callback function to retrieve default tracker data.

This function is called after a default tracker has been created.

The default tracker is passed as the first and only argument to this function. This argument is ‘undefined’ if no default tracker has been created.

For example, if you want to retrieve Client Id using the default tracker, then you can do that by using the following code:

ga(function(tracker) {

var clientId = tracker.get('clientId'); // get client ID from default tracker

console.log(clientId);

});

To validate this code, just copy paste it into the Google developer console and then press enter:

consoleOutput-1

You can retrieve the default tracker name by using the following code:

ga(function(tracker) {

var trackerName = tracker.get('name'); // get default tracker name

console.log(trackerName);

});

To validate this code, just copy-paste it into the Google developer console and then press enter:

consoleOutput-2

To retrieve tracking id, use the following code:

ga(function(tracker) {

var trackingId = tracker.get('trackingId');

console.log(trackingId);

});
output tracking id

To see how the default tracking object actually looks like, use the following code:

ga(function(tracker) {

 console.log(tracker);

});
default tracking object

Retrieving data stored on a user-defined tracker

If you are not using a default tracker or if you are using multiple trackers on a page, then you can retrieve data from a user-defined tracker by using getByName and getAll methods in a ready callback function.

You need to use the ready callback function because ga object methods (like getByName and getAll) are only available when analytics.js has fully loaded and ready, so you need to reference them inside a ready callback function.

Note: you can’t use get method directly on a user-defined tracker (also known as named tracker).

For example, if you want to retrieve the name of the user-defined tracker, then the following code won’t work:

ga(function() {

var trackerName = testProperty.get('name'); // can't use get method directly on named tracker

console.log(trackerName);

});

To retrieve the name and other data of a user-defined tracker, you need to use either the getByName method or getAll method.

getByName method

If you want to retrieve the name of user-defined tracker, you can use the following code:

ga(function() {

var nonDefaultTracker = ga.getByName('testProperty');

var trackerName = nonDefaultTracker.get('name'); // get the name of user defined tracker

console.log(trackerName); // write tracker name to developers console

});

If you want to retrieve the client ID of user-defined tracker, you can use the following code:

ga(function() {

var nonDefaultTracker = ga.getByName('testProperty');

var clientID = nonDefaultTracker.get('clientId'); // get the client id of user defined tracker

console.log(clientID); // write client id to developers console

});

If you want to retrieve the tracking ID of a user-defined tracker, you can use the following code:

ga(function() {

var nonDefaultTracker = ga.getByName('testProperty');

var trackingID = nonDefaultTracker.get('trackingId'); // get the tracking id of the user defined tracker

console.log(trackingID); // write tracking id to developers console

});

You can also retrieve the name, client id and tracking id of a user-defined tracker in one go, by using the following code:

ga(function() {

var nonDefaultTracker = ga.getByName('testProperty');

var trackerName = nonDefaultTracker.get('name'); // get the name of user defined tracker

var clientID = nonDefaultTracker.get('clientId'); // get the client id of user defined tracker

var trackingID = nonDefaultTracker.get('trackingId'); // get the tracking id of the user defined tracker

console.log(trackerName); // write tracker name to developers console

console.log(clientID); // write client id to developers console

console.log(trackingID); // write tracking id to developers console

});

Copy-paste this code into the developer console to validate it:

output named tracker

getAll method

This method is used to get an array of all created trackers.

The ga.getAll()[0] array element refers to the default tracker.

The ga.getAll()[1] array element refers to the first non-default tracker

The ga.getAll()[2] array element refers to the second non-default tracker

For example, if you want to retrieve the name of the default tracker, you can do that by using the following code:

ga(function() {

console.log(ga.getAll()[0].get('name'));

});

The output of this code would be: ‘t0’ which is the name of the default tracker.

If you want to retrieve the name of the first non-default tracker, you can do that by using the following code:

ga(function() {

console.log(ga.getAll()[1].get('name'));

});

The output of this code would be: ‘testProperty’, because that is the name of the second tracker I use:

second tracker name

But since I use only two trackers, any attempt to retrieve data from the third tracker will not work and I will get ‘undefined’ as output. For example:

ga(function() {

console.log(ga.getAll()[2].get('name'));

});

Here I am trying to retrieve the name of the third tracking object, which does not exist, so I will get ‘undefined’ as output:

third tracker

To retrieve the client Id and property ID of the first non-default tracker (or named tracker), you can use the following code:

ga(function() {

console.log(ga.getAll()[1].get('clientId'));

console.log(ga.getAll()[1].get('trackingId'));

});
client tracking id

Updating the default tracker data

You can update the default tracker data by using the set command method in the ga() command queue function or by using the set method on the default tracker itself.

Following is an example of using the set command method in the ga() command queue function, in order to update the default tracker data:

ga('set', 'page', '/virtual/download-seo-guide');

Here, page is the path portion of the URL whose value starts with a forward slash ‘/’.

Following is an example of using the set method on the default tracker itself, in order to update the default tracker data:

ga(function(tracker) {

tracker.set('page', '/virtual/download-seo-guide');

var page = tracker.get('page');

console.log(page);

});
tracker page output

Updating the named tracker data

Google Analytics refer to the user-defined tracker as named tracker.

You can update the named tracker data by using the set command method in the ga() command queue function or by using the set method on the named tracker itself.

Following is an example of using the set command method in the ga() command queue function, in order to update the named tracker data:

ga('testProperty.set', 'page', '/virtual/download-seo-guide');

Following is an example of using the set method on the named tracker itself, in order to update the named tracker data:

ga(function() {

var namedTracker = ga.getByName('testProperty');

namedTracker.set('page', '/download-seo-guide');

console.log(namedTracker.get('page'));

});
multiple trackers cross domain named tracker data

Sending data via default tracker

You can send data via the default tracker data by using the set command method in the ga() command queue function or by using the send method on the default tracker itself.

Following is an example of using the send command method in the ga() command queue function, in order to send pageview data via the default tracker:

ga('send', 'pageview');

Following is an example of using the send method on the default tracker itself, in order to send pageview data via the default tracker:

ga(function(tracker) {

tracker.send('pageview');

});

Following is an example of using the send method on the default tracker itself, in order to send event data via the default tracker:

ga(function(tracker) {

tracker.send('event','videos','Play','chappy',100);

});

Sending data via named tracker

You can send data via the named tracker data by using the set command method in the ga() command queue function or by using the send method on the named tracker itself.

Following is an example of using the send command method in the ga() command queue function, in order to send pageview data via the named tracker:

ga('testProperty.send', 'pageview');

Following is an example of using the send method on the named tracker itself, in order to send pageview data via the named tracker:

ga(function() {

var namedTracker = ga.getByName('testProperty');

namedTracker.send('pageview');

});

Following is an example of using the send method on the named tracker itself, in order to send event data via the named tracker:

ga(function(tracker) {

var namedTracker = ga.getByName('testProperty');

namedTracker.send('event','videos','Play','chappy',100);

});

Enough of theory now.

Let us use the concept of trackers to solve real work-life problems.

Using multiple trackers for cross-domain tracking in Google Analytics

Let us suppose you are using multiple trackers for roll-up reporting and you need to implement cross-domain tracking on top of that. Now how you will do that?

Before I start, let us do a quick recap of a roll-up property.

Quick recap of a roll-up property

In Google Analytics, a website or mobile application is called a property (also known as web property or digital property).

Unless you are a marketing agency/consultant, you are most likely to have access to only one Google Analytics account and only one Web property.

In Google Analytics each property is identified by a unique ID known as property ID (or tracking ID).

This tracking ID is in the format: UA-1235-23

Each property contains one or more views and each view contain multiple reports:

multiple trackers cross domain properties and views

A roll up property is the web property whose hit data comes from other Google Analytics properties.

multiple trackers cross domain google analytics rollup property

These other properties are known as ‘Source Properties‘ in Google Analytics lingo.

For example in the chart above, property-1, property-2, and property-N are source properties.

The roll-up property contains hit data from property-1, property-2, and property-N

Since each property in Google Analytics represents a website/mobile application, a roll-up property contains data from multiple websites/mobile applications.

Following is another way of looking at the roll-up property:

multiple trackers cross domain google analytics rollup property2

Just like any other property in GA, a roll-up property can also contain one or more views.

These views are called roll-up views:

multiple trackers cross domain roll up web property

These roll-up views contain multiple reports. The reports contain hit data from two or more websites/apps.

So if you own multiple websites or treat your subdomains as different websites then a roll-up property could be useful for you.

Note: To learn more about roll-up properties, check out this article: Implementing rollup reporting in Google Analytics.

Cross-domain tracking via multiple trackers

multiple trackers cross domain crossDomainTracking

What we are going to do here, is use two tracking objects for each web property.

So in the case of abc.com, the first tracking object (or default tracking object) is used to send hit data to abc.com. The second tracking object is used to share abc.com hit data with the rollup property.

Similarly, in the case of xyz.com, the first tracking object (or default tracking object) is used to send hit data to xyz.com. The second tracking object is used to share xyz.com hit data with the rollup property.

At the same time, we will also implement cross-domain tracking between abc.com and xyz.com, so that we can track users’ activities across domains.

Follow the steps below to implement cross-domain tracking between two primary domains (abc.com and xyz.com) via multiple tracking objects:

Step-1: Create a new web property in your Google Analytics account which you will use as a rollup property (if you already don’t have a rollup property)

This rollup property will store hit data from both abc.com and xyz.com websites.

For this to happen, both websites abc.com and xyz.com have to share all of their hit data with the rollup property.

If you don’t use rollup property and simply share abc.com and xyz.com hit data with each other by using multiple trackers then both websites’ web property will contain data from two websites and thus make individual analysis of the websites very difficult.

Let us assume that the rollup property ID is: UA-12345-21

Step-2: Apply filter to your rollup view which adds hostname to the request URI:

multiple trackers cross domain add host name to request URI2

Following is the configuration for the filter:

Filter Type: Custom filter > Advanced

Field A: Hostname

Extract A: (.*)

Field B: Request URI

Extract B: (.*)

Output To: Request URI

Constructor: $A1$B1

You need this filter so that you can separate the traffic coming from two different websites in your rollup reports.

Step-3: Share abc.com hit data with rollup property

Now in order to share abc.com hit data with the rollup property, you need to create a new tracker in the GA tracking code of abc.com and use the new tracker to send hit data to the roll-up web property.

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

ga(‘create’, ‘UA-12343-1', ‘auto’);

ga(‘create’, ‘UA-12345-21', {‘name':’rollupProperty’}); // create new tracking object and name it rollupProperty

ga('send', 'pageview');  // send pageview data to xyz.com

ga(‘rollupProperty.send’, ‘pageview’); // send pageview data to rollup property

</script>

Step-4: Share xyz.com hit data with rollup property

Now in order to share xyz.com hit data with the rollup property, you need to create a new tracker in the UA tracking code of xyz.com and use the new tracker to send hit data to roll-up web property.

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

ga(‘create’, ‘UA-155467-2', ‘auto’);

ga(‘create’, ‘UA-12345-21', {‘name':’rollupProperty’}); // create new tracking object and name it rollupProperty

ga('send', 'pageview');  // send pageview data to xyz.com

ga(‘rollupProperty.send’, ‘pageview’); // send pageview data to rollup property

</script>

Step-5:

# Create a copy of the main view of the website abc.com. Name the new view ‘ABC Cross Domain Tracking View’. We have created this view in order to maintain one unfiltered view.

# Apply custom advanced filter to the new view which adds hostname (domain name) to the request URI.

# Add ‘abc.com’ in the referral exclusion list to avoid self-referral issues.

Step-6:

# Create a copy of the main view of the website xyz.com. Name the new view ‘XYZ Cross Domain Tracking View’.

# Apply custom advanced filter to the new view which adds hostname to the request URI.

# Add ‘xyz.com’ to the referral exclusion list to avoid self-referral issues.

Step-7: Setup cross-domain tracking between abc.com and xyz.com

The auto-link plugin is used to track cross-domain traffic in Google Analytics.

Google recommends implementing cross-domain tracking via this plugin.

In order to use this plugin, you need to modify the GA tracking code of both websites abc.com and xyz.com.

Modify the Google analytics tracking code of the website abc.com as shown below:

<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-12343-1', ‘auto’,{'allowLinker': true }); // set allowLinker to true

ga(‘create’, ‘UA-12345-21', {‘name':'rollupProperty','allowLinker': true}); // set allowLinker to true for rollupProperty

ga('require', 'linker');// setup autoLink plugin

ga('rollupProperty.require', 'linker');// setup autoLink plugin for rollup property

ga('linker:autoLink', ['xyz.com']);// Auto link to xyz website

ga('rollupProperty.linker:autoLink', ['xyz.com']);// Auto link to xyz website

ga('send', 'pageview');

ga(‘rollupProperty.send’, ‘pageview’); // send pageview data to rollup property

</script>

Similarly, modify the Google Analytics tracking code of the website xyz.com as shown below:

<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-155467-2', {'allowLinker': true }); // set allowLinker to true

ga(‘create’, ‘UA-12345-21', {'name':'rollupProperty','allowLinker': true});// set allowLinker to true for rollupProperty

ga('require', 'linker');// setup autoLink plugin

ga('rollupProperty.require', 'linker');// setup autoLink plugin for rollup property

ga('linker:autoLink', ['abc.com']);// Auto link to abc website

ga('rollupProperty.linker:autoLink', ['abc.com']);// Auto link to abc website

ga('send', 'pageview');

ga(‘rollupProperty.send’, ‘pageview’); // send pageview data to rollup property

</script>

To learn more about cross-domain tracking, check out the following articles:

  1. Google & Universal Analytics Cookies
  2. Google Analytics Cross-Domain Tracking
  3. Cross-Domain Tracking in Universal Analytics
  4. Cross-Domain Tracking in Google Tag Manager

 Other article you will find useful: Creating your own Google Analytics Tag Auditing System

Other articles on specialized tracking in Google Analytics

  1. Google Analytics Ecommerce Tracking Tutorial
  2. Google Tag Manager Event Tracking Tutorial
  3. Google Analytics Event Tracking Tutorial
  4. Google Analytics Store Visits Tracking Tutorial
  5. Offline Conversion Tracking in Google Analytics – Tutorial
  6. Ecommerce Tracking Google Tag Manager (GTM) – Tutorial
  7. Tracking Virtual Pageviews in Google Tag Manager – Tutorial
  8. Google Tag Manager YouTube Video Tracking
  9. How to unlock not provided keywords in Google Analytics?
  10. Google Analytics Virtual Pageviews Tutorial
  11. Google Analytics and YouTube Integration Tutorial
  12. Google Analytics for Facebook Tutorial
  13. Cross Domain Tracking in Google Analytics – Complete Guide
  14. The one thing that you don’t know about PayPal.com and the referral exclusion list
  15. Google Analytics Calculated Metrics – Tutorial
  16. Creating your own Google Analytics Tag Auditing System
  17. Google Tag Manager Search Tracking without Query Parameter
  18. Tracking Google Analytics Paypal Referral and other payment gateways
  19. How to Track Phone Calls in Google Analytics – Call Tracking Tutorial
  20. How to track leads in Google Analytics via CRM
  21. Postbacks in Google Analytics Explained
  22. Subscription & Recurring Revenue Analytics in Google Analytics
  23. Track the Impact of Google Analytics Cookie Consent on Website Traffic
  24. Tracking Offline Conversions in Google Ads
  25. Implementing Scroll Tracking via Google Tag Manager
  26. Scroll Depth Tracking in Google Tag Manager – Tutorial
  27. Site Search Tracking In Google Analytics Without Query Parameters
  28. Google Tag Manager Youtube Video Tracking via YouTube Video Trigger
  29. How to Correctly Measure Conversion Date & Time in Google Analytics
  30. Google Analytics Social Tracking – Twitter, Facebook, Google Plus and LinkedIn
  31. Cross Domain Tracking in Google Analytics – Complete Guide
  32. Google Analytics Linkedin & Twitter Tracking
  33. Creating Content Group in Google Analytics via tracking code using gtag.js
  34. Google Analytics Site Search Tracking via Query Parameters
  35. Google Analytics Site Search Tracking Tutorial
  36. Creating and Using Site Search Funnel in Google Analytics
  37. Learn to Setup Facebook Pixel Tracking via Google Tag Manager
  38. AMP Google Analytics Tracking – Learn to track AMP pages
  39. Setting up Sales Funnel across websites in Google Analytics
  40. Regex Google Analytics & Google Tag Manager – Tutorial

Frequently asked questions about how to use two Google Analytics codes on one page

Can I use two Google Analytics codes on one page?

If you want to send data to multiple web properties from a single web page then you need to understand what trackers are and how they can be created and used. 

You need to create two tracking objects if you want to send hit data to two web properties from a single web page:

Similarly, if you want to send website usage data to 3 web properties (3 websites/apps) from a single web page then you need to create and use three trackers.

What is a tracking object?

Tracking object (also known as tracker) is used to send hit data (pageviews, screenviews, events, transactions, etc) to a Google Analytics (GA) web property:

Without first creating and using a tracking object, you can not send hit data to a GA property.

Google Analytics ‘create’ command is used to create a tracking object. This command also associates the tracking object with a web property.

For example, the following line of code creates a default tracking object through Google Analytics ‘create’ command and then associate the tracking object with the web property whose id is ‘UA-12345-12’:

ga(‘create’, {‘trackingId’: ‘UA-12345-12’},’auto’);

What are the different types of tracking objects?

There are two types of tracking objects: default and user-defined tracking objects.

Google refers to user defined trackers as named trackers. So named trackers and user defined trackers are same thing.

What is a roll up property?

A roll up property is a web property whose hit data comes from other Google Analytics properties.

Since each property in Google Analytics represents a website/mobile application, a roll up property contains data from multiple websites/mobile applications.

Register for the FREE TRAINING...

"How to use Digital Analytics to generate floods of new Sales and Customers without spending years figuring everything out on your own."



Here’s what we’re going to cover in this training…

#1 Why digital analytics is the key to online business success.

​#2 The number 1 reason why most marketers are not able to scale their advertising and maximize sales.

#3 Why Google and Facebook ads don’t work for most businesses & how to make them work.

#4 ​Why you won’t get any competitive advantage in the marketplace just by knowing Google Analytics.

#5 The number 1 reason why conversion optimization is not working for your business.

#6 How to advertise on any marketing platform for FREE with an unlimited budget.

​#7 How to learn and master digital analytics and conversion optimization in record time.



   

My best selling books on Digital Analytics and Conversion Optimization

Maths and Stats for Web Analytics and Conversion Optimization
This expert guide will teach you how to leverage the knowledge of maths and statistics in order to accurately interpret data and take actions, which can quickly improve the bottom-line of your online business.

Master the Essentials of Email Marketing Analytics
This book focuses solely on the ‘analytics’ that power your email marketing optimization program and will help you dramatically reduce your cost per acquisition and increase marketing ROI by tracking the performance of the various KPIs and metrics used for email marketing.

Attribution Modelling in Google Analytics and BeyondSECOND EDITION OUT NOW!
Attribution modelling is the process of determining the most effective marketing channels for investment. This book has been written to help you implement attribution modelling. It will teach you how to leverage the knowledge of attribution modelling in order to allocate marketing budget and understand buying behaviour.

Attribution Modelling in Google Ads and Facebook
This book has been written to help you implement attribution modelling in Google Ads (Google AdWords) and Facebook. It will teach you, how to leverage the knowledge of attribution modelling in order to understand the customer purchasing journey and determine the most effective marketing channels for investment.

About the Author

Himanshu Sharma

  • Founder, OptimizeSmart.com
  • Over 15 years of experience in digital analytics and marketing
  • Author of four best-selling books on digital analytics and conversion optimization
  • Nominated for Digital Analytics Association Awards for Excellence
  • Runs one of the most popular blogs in the world on digital analytics
  • Consultant to countless small and big businesses over the decade
error: Alert: Content is protected !!