Google Analytics

Reference - Complete Web Upgrade: ga.js / dc.js to analytics.js

This reference guide shows how to retag your website to use analytics.js after you have transferred your property to Universal Analytics.

  1. Overview
  2. Before you Begin
  3. Configuring Exclusions, Search Engines, and Timeouts
    1. Custom Search Engines
    2. Referral Exclusions
    3. Search Term Exclusions
  1. Replacing the Basic Snippet
  2. Events
  3. Ecommerce
  4. Custom Variables
  5. Virtual Pageviews
  6. Social Interactions
  7. User Timings
  8. Cross Domain Tracking
  9. Subdirectory Tracking
  10. Sampling
  11. Working with Multiple Cookies
  12. Enhanced Link Attribution
  13. Enabling Display Features

Overview

The analytics.js library is the latest JavaScript library for Google Analytics designed to take advantage of all the new features of the Universal Analytics platform.

Current ga.js and dc.js users can use this guide to learn how to modify their code and configuration settings in order to complete the upgrade to the analytics.js library.

Before you Begin

You must transfer your property to Universal Analytics before retagging your site with analytics.js Review the following caveats before modifying your code:

  • Once you have transferred a property to Universal Analytics, the session timeout and campaign timeout periods must be configured via the Google Analytics Admin page and not in your code. Calls to _setSessionCookieTimeout or _setCampaignCookieTimeout will be ignored once a property is transferred to Universal Analytics.

  • If you use multiple trackers on each page, expect to see a small, temporary increase of new users relative to return users after updating your code. This is expected behavior and due to differences in the way sessions are processed in Universal Analytics.

  • If you are currently hosting ga.js locally and use multiple trackers on each page, you will need to get a fresh version of the library before upgrading to Universal Analytics in order to avoid additional discrepancies in new and returning user metrics.

Configuring Exclusions, Search Engines, and Timeouts

Begin the retagging process by migrating any necessary custom search engines or exclusions from your ga.js code to the Google Analytics Admin page. The following sections document how to configure each of these settings from the Google Analytics Admin page.

Custom Search Engines

Google Analytics recognizes a number of search engines by default. If you want to add a custom search engine you can configure this from the Google Analytics Admin page. Any custom search engines that you have previously configured in ga.js using the _addOrganic method should now be configured from the Google Analytics Admin page.

Referral Exclusions

Referring domains maybe be excluded from reports in Universal Analytics from the Google Analytics Admin page. Learn how to exclude referrers (Help Center). Any referral exclusions that you have previously configured in ga.js using _addIgnoredRef method should now be configured from the Google Analytics Admin page.

Search Term Exclusions

Organic search terms can be excluded in Universal Analytics via the management interface. Learn how to exclude search terms (Help Center). Any search terms that you have previously configured Google Analytics to ignore using the _addIgnoredOrganic method should now be configured from the Google Analytics Admin page.

Timeout Handling

Session and campaign timeouts can be set in Universal Analytics from the Google Analytics Admin page. Learn how to configure campaign and session timeout (Help Center). Any timeouts that you have previously configured in ga.js using the _setSessionCookieTimeout and _setCampaignCookieTimeout methods should now be configured from the Google Analytics Admin page.

Replacing the Basic Snippet

To enable basic page tracking with analytics.js, replace the original ga.js code snippet with the following analytics.js code on every page.

analytics.js (Universal Analytics)

<!-- Google Analytics -->
<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-XXXX-Y', 'auto');  // Replace with your property ID.
ga('send', 'pageview');

</script>
<!-- End Google Analytics -->

Events

The syntax for sending events has changed in analytics.js. If you use events, you will need to change your code to send events using the following syntax:

analytics.js (Universal Analytics)

ga('send', 'event', 'category', 'action', 'opt_label', opt_value, {'nonInteraction': 1});

For more details, see the analytics.js Events Developer Guide.

Ecommerce

The syntax for measuring ecommerce activity has changed. To measure ecommerce activity using analytics.js, your code will need to be updated to load the new ecommerce plug-in after you create the tracker object and send any initial pageviews, as in this example:

analytics.js (Universal Analytics)

ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
ga('require', 'ecommerce', 'ecommerce.js');   // Load the ecommerce plug-in.

Next, update your code to add transaction data using the addTransaction command:

ga('ecommerce:addTransaction', {
  'id': '1234',                     // Transaction ID. Required
  'affiliation': 'Acme Clothing',   // Affiliation or store name
  'revenue': '11.99',               // Grand Total
  'shipping': '5',                  // Shipping
  'tax': '1.29'                     // Tax
});

Likewise, update to your code to add item data by using the addItem command for each item belonging to the transaction:

// addItem should be called for every item in the shopping cart.
ga('ecommerce:addItem', {
  'id': '1234',                     // Transaction ID. Required
  'name': 'T-Shirt',                // Product name. Required
  'sku': 'DD44',                    // SKU/code
  'category': 'Green Medium',       // Category or variation
  'price': '11.99',                 // Unit price
  'quantity': '1'                   // Quantity
});

Lastly, update your code to send the transaction and item data to Google Analytics using the send command and ecommerce hit type:

ga('ecommerce:send');      // Send transaction and item data to Google Analytics.

For more details, see the analytics.js Ecommerce Developer Guide.

Custom Variables

Custom variables have been replaced by custom dimensions in analytics.js and Universal Analytics. Although similar to custom variables, the name and scope of custom dimensions are configured via the Admin page, rather than in your code. Before sending any custom dimension data to Google Analytics, Learn how to configure a custom dimension (Help Center).

For example, to send a value for a 'Customer Type' custom dimension with User scope, the first step would be to create and configure a custom dimension in the Admin page using the following values:

Name : Customer Type
Scope : User

An numerical index will also be automatically assigned to the custom dimension.

Next, set the Customer Type of a user in your code using the set command and the dimension[index] field, where index corresponds to the index of the dimension found in the Admin page:

analytics.js (Universal Analytics)

ga('set', 'dimension1', 'Paid');

For more details, see the analytics.js Custom Dimensions & Metrics Developer Guide.

Virtual Pageviews

The syntax for sending virtual pageviews has changed. If you use virtual pageviews, you must update your code to use the new analytics.js syntax:

analytics.js (Universal Analytics)

ga('send', 'pageview', 'page path');

For more details, see the analytics.js Page Tracking Developer Guide.

Social Interactions

The syntax for sending social interactions with analytics.js has changed. If you use social interactions, you must update your code to use the new analytics.js syntax:

analytics.js (Universal Analytics)

ga('send', 'social', 'socialNetwork', 'socialAction', 'socialTarget', {'page': 'optPagePath'});

For more details, see the analytics.js Social Interactions Developer Guide.

User Timings

The syntax for sending user timings has changed. If you use user timings, you must update your code to use the new analytics.js syntax:

analytics.js (Universal Analytics)

ga('send', 'timing', 'timingCategory', 'timingVariable', timingValue, 'optLabel');

For more details, see the analytics.js User Timings Developer Guide.

Cross Domain Tracking

Cross domain tracking has changed in analytics.js and is not compatible with cross domain tracking in ga.js. Both the source and destination domains need to be using the same code in order to track user interactions across them in a single session.

Tracking user interactions across a top level domain and its subdomains requires the basic analytics.js snippet to be modified in the following way on all pages:

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

Tracking user interactions across a source domain and any destination domain(s) in a single session with analytics.js requires the following code:

analytics.js (Universal Analytics)

// On the Origin Domain
ga('create', 'UA-XXXX-Y', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['destination.com']);      // Domains that are linked from this page.
ga('send', 'pageview');                          // Send hits after initializing the auto-linker plug-in.

// On the Destination Domain
ga('create', 'UA-XXXX-Y', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['source.com']);       // Domains that are linked from this page.
ga('send', 'pageview');                      // Send hits after initializing the auto-linker plug-in.

If you would like to keep the code the same on every domain, include every domain in the list.

// On every domain.
ga('create', 'UA-XXXX-Y', 'auto', {'allowLinker': true});
ga('require', 'linker');

// List of every domain to share linker parameters.
ga('linker:autoLink', ['source.com', 'destination.com']);
ga('send', 'pageview'); // Send hits after initializing the auto-linker plug-in.

This will decorate links between www.source.com and source.com, which is unncessary but harmless. It will not decoreate links to and from the same exact hostname.

By using this code, the Auto Link plug-in will automatically enable cross domain tracking using the domains you specify by tagging any links on the page pointing to those domains. Learn more about the Auto Link plug-in.

For advanced cross domain tracking use cases, including tracking across iframes, sending form data across domains, and more, see the analytics.js Cross Domain Developer Guide.

Subdirectory Tracking

If you need to restrict tracking to a single subdirectory or path, the required code has changed and will need to be updated to use the following analytics.js syntax:

analytics.js (Universal Analytics)

// cookiePath must be set when create is called.
ga('create', 'UA-XXXX-Y', 'auto', {'cookiePath': '/tracked-dir/'});

Sampling

Enable client-side sampling with analytics.js by setting the sampleRate field when the create command is called, as in the following example:

// Sample rate must be set in create method.
ga('create', 'UA-XXXX-Y', 'auto', {'sampleRate': 5});

Working with Multiple Cookies

The following sections describe how to handle advanced migration scenarios when working with multiple sets of Google Analytics cookies:

Managing Cookies with ga.js and analytics.js on the Same Website

Additional configuration may be required in cases where cookie information needs to be transferred from a Universal Analytics cookie to classic Google Analytics cookies set by ga.js, such as with larger websites that have not completely retagged with analytics.js and have both tracking codes present for some period of time:

Custom Cookie Names

If you are setting the cookie name of your analytics.js tracker to a custom value, you also must set that same cookie name value in your ga.js implementation by setting the uaName field:

// analytics.js
ga('create', 'UA-XXXX-Y', 'auto', {cookieName: 'myCookieName'});

...

// ga.js
_gaq.push(['_set', 'uaName', 'myCookieName']);

Custom Cookie Paths

If you are planning to use multiple analytics.js trackers with different cookie domains and/or cookie paths, you must likewise update your ga.js trackers using uaDomain and uaPath, respectively:

// analytics.js
ga('create', 'UA-XXXX-Y', 'auto', {cookiePath: '/myPath/'});

...

// Specify the path of the Universal Analtyics cookie with ga.js
_gaq.push(['_set', 'uaPath', '/myPath/']);
// analytics.js
ga('create', 'UA-XXXX-Y', {cookieDomain: 'blog.example.com'});

...

// Specify the domain of the Universal Analtyics cookie with ga.js
_gaq.push(['_set', 'uaDomain', 'blog.example.com']);

Custom Cookie Subdomains

If your website has multiple sets of visible Google Analytics cookies, set in ga.js using _setCookiePath, you can specify which set of cookies you would like migrated to analytics.js by using the legacyCookiePath field, as in this example:

// Explicitly migrate the GA cookies set on this subdomain to analytics.js.
ga('create', 'UA-XXXX-Y', {'legacyCookieDomain': 'blog.example.com'});

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

Learn more about the Enhanced Link Attribution plug-in.

Enabling Display Features

The display features plugin for analytics.js can be used to enable Display Advertising Features in Google Analytics, such as Remarketing, Demographics and Interest Reporting, and more. Learn more about Display Advertising Features in Google Analytics

In the past, this functionality required using the dc.js tag. In Universal Analytics, these features are enabled via a plugin. To load the plugin, add a require call to your code snippet, specifying the displayfeatures plugin:

ga('create', 'UA-XXXX-Y', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.