Google Analytics

Advanced Configuration - Web Tracking (analytics.js)

This document provides an overview of the analytics.js collection library.

  1. The JavaScript Snippet
  2. Creating Tracker Objects
    1. Customizing Tracker Objects
    2. Testing on localhost
  1. Sending Data
    1. Field Name Object
    2. Hit Callback
    3. Setting Parameters
    4. Pushing Functions
    5. Getting Parameters
    6. Forcing SSL (HTTPS)
  1. Multiple Tracking Objects
  2. Enhanced Link Attribution
  3. IP Anonymization
  4. User Opt-out

The JavaScript Snippet

To enable Google Analytics on your site, you add a piece of JavaScript before the closing </head> tag of your page. Here's a portion of the snippet:

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

When the snippet runs, it first creates an new global function named ga. Next, the snippet asynchronously loads the analytics.js library onto the page.

The ga global function is the main way you interact with the analytics.js library. The function accepts a sequence of parameters, where the first parameter represents a Google Analytics command. For example, in the default snippet:

ga('create', 'UA-XXXX-Y', 'auto');  // Creates a tracker.
ga('send', 'pageview');             // Sends a pageview.

The first line calls the create command, and the second line calls the send command.

Even though the JavaScript loads the analytics.js library asynchronously, the ga function is designed to be used before the library has loaded. When you first start executing commands, each command is added to a queue. Once the library is done loading, all commands in the queue are executed, and new commands are executed immediately. This lets developers ignore the asynchronous nature of Google Analytics and focus on using the ga function.

Renaming the Global Object

In some cases the ga variable name might already be used by an existing object on your page. To avoid overriding your existing object, you can rename the ga function, for example to __gaTracker. To do this, simply replace the ga parameter in the snippet above:

(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','__gaTracker');


Then you can use __gaTracker instead of ga when calling commands:

__gaTracker('create', 'UA-XXXX-Y', 'auto');
__gaTracker('send', 'pageview');

JavaScript Snippet Reference

The following reference shows the basic JavaScript snippet with comments and whitespace added:

<!-- Google Analytics -->
<script>
/**
 * Creates a temporary global ga object and loads analy  tics.js.
 * Paramenters o, a, and m are all used internally.  They could have been declared using 'var',
 * instead they are declared as parameters to save 4 bytes ('var ').
 *
 * @param {Window}      i The global context object.
 * @param {Document}    s The DOM document object.
 * @param {string}      o Must be 'script'.
 * @param {string}      g URL of the analytics.js script. Inherits protocol from page.
 * @param {string}      r Global name of analytics object.  Defaults to 'ga'.
 * @param {DOMElement?} a Async script tag.
 * @param {DOMElement?} m First script tag in document.
 */
(function(i, s, o, g, r, a, m){
  i['GoogleAnalyticsObject'] = r; // Acts as a pointer to support renaming.

  // Creates an initial ga() function.  The queued commands will be executed once analytics.js loads.
  i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
  },

  // Sets the time (as an integer) this tag was executed.  Used for timing hits.
  i[r].l = 1 * new Date();

  // Insert the script tag asynchronously.  Inserts above current tag to prevent blocking in
  // addition to using the async attribute.
  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-XXXX-Y', 'auto'); // Creates the tracker with default parameters.
ga('send', 'pageview');            // Sends a pageview hit.
</script>
<!-- End Google Analytics -->

Creating Tracker Objects

To send data to Google Analytics, you must create a tracking object. Each tracking object can send data to a single Google Analytics web property. To create a tracking object, the default snippet uses the following code:

ga('create', 'UA-XXXX-Y', 'auto');

Where the first parameter to the ga function is the create command, and the second parameter is the web property ID to which to send data.

Customizing Tracker Objects

All tracking object customization must be done when the object is initially created, by passing the ga function a configuration object as the last parameter. For example to override some of the cookie settings, you would use:

ga('create', 'UA-12345-6', {
   'cookieDomain': 'foo.example.com',
   'cookieName': 'myNewName',
   'cookieExpires': 20000
});

In the example above, the cookie domain, name, and expiration time have all been modified through the optional configuration object.

Read the create only section in the Field Reference document for complete details on all the fields that may be configured in the create command.

Testing on localhost

In some cases you might want to test analytics.js from a webserver running on localhost. To set analytics.js cookies, you need to disable the default cookie domain using:

ga('create', 'UA-XXXX-Y', {
  'cookieDomain': 'none'
});

Sending Data

Once a tracking object is created and associated with a web property, you can use the send command to send data to that web property. The data you send to Google Analytics is called a Hit, and the analytics.js library allows you to send various types of data by specifying a hitType. When you use the send command, you must also specify the hitType of data you want to send.

For example to send a pageview hit, you use:

ga('send', 'pageview');

This sends data for the default URL to Google Analytics.

Field Name Object

In some cases you might want to override multiple values that are sent as a pageview. The analytics.js library allows you to pass a field name object as the last parameter in the send command. This is useful as it allows you to set many additional properties of the pageview, for example the page title:

ga('send', 'pageview', {
  'page': '/my-new-page',
  'title': 'My New Page Title'
});

Read the Field Reference document for complete details on all the ways a tracker object may be configured.

Setting the Hit Callback

In some cases, like when you track outbound links, you might want to know when the tracker is done sending data. That way you can send a user to their destination only after their click has been reported to Google Analytics. To solve this, the send command allows you to specify a hitCallback function in the field name object that will execute as soon as analytics.js has completed sending data. Here's how to set the hitCallback function:

ga('send', 'pageview', {
  'page': '/my-new-page',
  'hitCallback': function() {
    alert('analytics.js done sending data');
  }
});

In this example, the field name object configures both the page parameter, as well as setting the hitCallback. Once the tracker has completed sending data, an alert box will be shown to the user.

Setting Parameters Across Multiple Send Commands

In some cases you might want to set a parameter and have the value persist across multiple send commands. For example, if you have a webpage in which you want to track one pageview and two events. If you wanted to override the page path of each hit with your own custom path, you could either set the new path on each send command, or you can use the set method like this:

ga('set', 'page', '/my-custom-page');

ga('send', 'pageview');
ga('send', 'event', 'image1', 'clicked');
ga('send', 'event', 'image2', 'clicked');

When the following code is executed, the overridden page /my-custom-page will be sent for all 3 send commands.

Pushing Functions

Sometime you will want to execute code only once the analytics.js library has loaded. To do this you can pass a function as a parameter to the ga function.

ga(function() {
  alert('library done loading');
});

Once the library is done loading, the user will see an alert box.

Getting Parameters

With analytics.js, you can retrieve any of the values that have been set in the tracking object using the get command. Because the tracker object is only created once the library has loaded, you must get parameters within a pushed function.

ga(function(tracker) {
  var defaultPage = tracker.get('page');
});

In this example, the function uses a parameter named tracker. Once the library is done loading, the function will execute and the value of tracker will be the default tracking object that has been created as a result of the first create command. The tracker is then used to get the default page value.

Forcing SSL (HTTPS)

"By default, Google Analytics will match the protocol of the host page when sending outbound requests. To force Google Analytics to always send data using SSL, even from insecure pages (HTTP), set the forceSSL field to true:

ga('create', 'UA-XXXX-Y', 'auto');
ga('set', 'forceSSL', true);        // Send all data using SSL, even from insecure (HTTP) pages.
ga('send', 'pageview');

Working with Multiple Tracking Objects

In some cases you might want to send data to multiple web properties from a single page. This is useful for sites that have multiple owners overseeing sections of a site; each owner could view their own web property.

To solve this, you must create a tracking object for each web property to which you want to send data:

ga('create', 'UA-XXXX-Y', 'auto');
ga('create', 'UA-12345-6', 'auto', {'name': 'newTracker'});  // New tracker.

Once run, two tracker objects will be created. The first tracker will be the default tracking object, and not have a name. The second tracker will have the name of newTracker.

To send a pageview using both trackers, you prepend the name of the tracker to the beginning of the command, followed by a dot. So for example:

ga('send', 'pageview');
ga('newTracker.send', 'pageview'); // Send page view for new tracker.

Would send a pageview to both default and new trackers.

To access a tracker object by name within a function, you use the getByName method:

ga(function() {
  var newTracker = ga.getByName('newTracker');
});

To get an array of all the trackers that have been configured, use the getAll method:

ga(function() {
  var allTrackers = ga.getAll();
});

Enhanced Link Attribution improves the accuracy of your In-Page Analytics report by automatically differentiating between multiple links to the same URL on a single page by using link element IDs.

To enable enhanced link attribution:

  1. Enable enhanced link attribution in the Admin UI of your Google Analytics account.
  2. Update your code on each page to load the Enhanced Link Attribution plug-in, as in this example:
ga('create', 'UA-XXXX-Y', 'auto');
ga('require', 'linkid', 'linkid.js'};   // Load the plug-in. Note: this call will block until the plug-in is loaded.
ga('send', 'pageview');

The enhanced link attribution plug-in differentiates between links to the same URL using the element IDs of a link or a parent element, as well as a cookie. You can customize how far up the DOM the plug-in will look for an element ID, as well as the behavior of this cookie, by providing configuration options when loading the plug-in:

ga('create', 'UA-XXXX-Y', 'auto');
ga('require', 'linkid', 'linkid.js', {
           'cookieName': '_ela',        // Cookie name. _gali by default.
           'duration': 45,              // Cookie duration. 30 seconds by default.
           'levels': 5});               // Max DOM levels from link to look for element ID. 3 by default.
ga('send', 'pageview');

IP Anonymization

In some cases, you might need to anonymize the IP address of the hit (http request) sent to Google Analytics. You can anonymize the IP addresses for all the hits sent from a page (the lifetime of the tracker object) by using the set command and setting the anonymizeIp field to true:

ga('set', 'anonymizeIp', true);

To anonymize the IP address of an individual hit, you can set the anonymizeIp field in the optional configuration object for that hit:

ga('send', 'pageview', {
  'anonymizeIp': true
});

To learn more about how IP anonymization works, read the IP Anonymization in Google Analytics article in the help center.

User Opt-out

In some cases, it may be necessary to disable the Google Analytics tracking code on a page without having to remove the JavaScript snippet. For example, you might do this if your site's privacy policy includes the ability for a visitor to opt-out of Google Analytics tracking.

The analytics.js library now includes a window property that, when set to true, disables analytics.js from sending data to Google Analytics. When Google Analytics attempts to set a cookie or send data back to the Google Analytics servers, it will check for whether this property is set to true. If it is, it will have the same effect as if the visitor had the Google Analytics Opt-out Browser Plugin installed.

To disable tracking, set the following window property to true:

window['ga-disable-UA-XXXX-Y'] = true;

Where the value UA-XXXX-Y corresponds to the web property ID on which you would like to disable tracking.

This window property must be set before the tracking code is called. This property must be set on each page where you want to disable Google Analytics tracking. If the property is not set or set to false then the tracking will work as usual.

Example

Here's a simple example of some code you can use to provide opt-out functionality for your users.

First, add a new HTML link to your site to execute the opt-out logic:

<a href="javascript:gaOptout()">Click here to opt-out of Google Analytics</a>

Then add the following snippet of code before the analytics.js code snippet. Make sure to replace the value of gaProperty from UA-XXXX-Y to the property used on your site. This is the same value that you pass to the create command.

<script>
// Set to the same value as the web property used on the site
var gaProperty = 'UA-XXXX-Y';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
}

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
}
</script>

When a user clicks the opt-out HTML link, the custom gaOptout function will execute. It will set a cookie for a long time in the future and disable analytics.js data collection. When a user returns to this site, the script above will check to see if the opt-out cookie has been set. If it has, then the analytics.js data collection will also be disabled.







Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.