Cookies and User Identification

Cookies and User Identification

In order for Google Analytics to determine that two distinct hits belong to the same user, a unique identifier, associated with that particular user, must be sent with each hit.

The analytics.js library accomplishes this via the Client ID field, a unique, randomly generated string that gets stored in the browsers cookies, so subsequent visits to the same site can be associated with the same user.

By default, analytics.js uses a single, first-party cookie named _ga to store the Client ID, but the cookie's name, domain, and expiration time can all be customized. Other cookies created by analytics.js include _gidAMP_TOKEN and_gac_<property-id>. These cookies store other randomly generated ids and campaign information about the user.

Using cookies allows analytics.js to identify unique users across browsing sessions, but it cannot identify unique users across different browsers or devices. If your site has its own authentication system, you can use the User ID feature, in addition to the Client ID, to more accurately identify a user across all the devices they use to access your site.

This guide explains how to customize the cookie settings as well as how to set the user ID field to more accurately track users across sessions.

Note: you can refer to the Cookie Usage guide for more information on how analytics.js uses cookies.

The following table shows the default cookie field values used by analytics.js:

Field NameValue TypeDefault value
cookieNametext_ga
cookieDomaintextThe result of the following JavaScript expression:
document.location.hostname
cookieExpiresinteger63072000 (two years, in seconds)

To modify any of these values, you can specify them in the fieldObject you pass the create command. For example:

 

ga('create', 'UA-XXXXX-Y', {
  'cookieName': 'gaCookie',
  'cookieDomain': 'blog.example.co.uk',
  'cookieExpires': 60 * 60 * 24 * 28  // Time in seconds.
});

The most common cookie field to set is cookieDomain, as such, the create command accepts the cookieDomainfield as an optional third parameter for convenience:

 

ga('create', 'UA-XXXXX-Y', 'blog.example.co.uk');

Note: The cookieDomain must be an ancestor of the current domain, otherwise the cookie will not get set. For example, if your domain is one.two.three.root.com, you may configure the cookie to be set on root.com, but not someotherdomain.com. Setting an incorrect cookie domain will result in no hits being sent to Google Analytics.

The recommended JavaScript tracking snippet sets the string 'auto' for the cookieDomain field:

 

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

Specifying 'auto' as the cookieDomain enables automatic cookie domain configuration, which tells analytics.js to automatically determine the best cookie domain to use.

Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

When using automatic cookie domain configuration, your users will be tracked across subdomains without any extra configuration.

Every time a hit is sent to Google Analytics, the cookie expiration time is updated to be the current time plus the value of the cookieExpires field. This means that if you use the default cookieExpires time of two years, and a user visits your site every month, their cookie will never expire.

If you set the cookieExpires time to 0 (zero) seconds, the cookie turns into a session based cookie and expires once the current browser session ends:

You should not directly access the cookie analytics.js sets, as the cookie format might change in the future. Instead, developers should use the readyCallback to wait until analytics.js is loaded, and then get the clientId value stored on the tracker.

 

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

Disabling Cookies

In some cases you might want to use your own storage mechanism (such as localStorage or a Service Worker) to persist the Client ID across sessions without using cookies. You can disable analytics.js from setting cookies by setting the storage field to 'none'.

 

ga('create', 'UA-XXXXX-Y', {
  'storage': 'none'
});

If you're storing the clientId field yourself, you'll need to make sure to set the cliendId field when you create the tracker.

 

ga('create', 'UA-XXXXX-Y', {
  'storage': 'none',
  'clientId': '76c24efd-ec42-492a-92df-c62cfd4540a3'
});

To disable the _gac_<property-id> cookies, set the storeGac field to false in the create command:

 

ga('create', 'UA-XXXXX-Y', {
  storeGac: false,
});

Using localStorage to store the Client ID

The following code sample shows how you could modify the JavaScript tracking snippet to use localStorage to store the Client ID rather than cookies:

 

var GA_LOCAL_STORAGE_KEY = 'ga:clientId';

if (window.localStorage) {
  ga('create', 'UA-XXXXX-Y', {
    'storage': 'none',
    'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
  });
  ga(function(tracker) {
    localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
  });
}
else {
  ga('create', 'UA-XXXXX-Y', 'auto');
}

ga('send', 'pageview');

Note: unlike cookies, localStorage is bound by the same-origin policy. If parts of your site are on different subdomains, or if some pages use http and others pages use https, you cannot use localStorage to track users between those pages. For this reason, cookies continues to be the officially recommended way to store the Client ID.

User ID

User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. To learn why you should implement the User ID, see Benefits of using the User ID feature.

To implement the User ID with analytics.js:

  1. Provide your own unique, persistent, and non-personally identifiable string ID to represent each signed-in user. This ID is most often provided by an authentication system.
  2. Set the User ID on the tracker:
 

ga('create', 'UA-XXXXX-Y', 'auto', {
  userId: USER_ID
});
ga('send', 'pageview');

Important! The USER_ID value should be a unique, persistent, and non-personally identifiable string identifier that represents a user or signed-in account across devices.

Handling authentication after pageload

When building Single Page Applications or other dynamic websites that handle user sign-in after the initial page load, the process of setting the user ID value on the tracker can't happen at creation time.

In such cases, you can use the set command to set the value on the tracker as soon as it's known.

 

// Creates the tracker and sends a pageview as normal
// since the `userId` value is not yet known.
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

// At a later time, once the `userId` value is known,
// sets the value on the tracker.
ga('set', 'userId', USER_ID);

// Setting the userId doesn't send data to Google Analytics.
// You must also use a pageview or event to send the data.
ga('send', 'event', 'authentication', 'user-id available');

When using this approach, hits sent before the userId field is set will not contain user ID values. However, through a process known as Session Unification, Google Analytics is able to associate these hits with the correct user at processing time.

Cross-domain measurement

This guide describes how to measure events across multiple domains using analytics.js.

Warning: Properly implementing cross-domain tracking is complex and error prone. This guide explains the concepts, but it's strongly recommended that you use the official Linker plugin instead of trying to implement cross-domain tracking yourself.

Overview

The analytics.js library uses a unique client ID to determine whether a user is new or returning. A user is considered returning if a hit with a matching client ID has already been sent to the same property.

By default, the client ID is stored in the browser's cookies, which means it can only be accessed by pages on the same domain. To track the same Client ID for a given user across different domains, use cross domain tracking.

To share a client ID across domains, you can append it as a query parameter to URLs that point from the current domain (the source domain) to the destination domain that you want to measure. When a user clicks on a link or submits a form on the source domain and navigates to the destination domain, code on the destination page can access the client ID by reading it from the URL.

Getting the client ID on the source domain

To retrieve a client ID on the source domain, you use the get method:

 

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

Once you have the client ID on the source domain, you can add it to links that point to the destination domain.

 

<a href="https://destination.com/?clientId=XXXXXX">destination.com</a>

Setting the client ID on the destination domain

You can tell a tracker object on the destination domain what client ID to use by specifying the client ID field in the create command:

 

ga('create', 'UA-XXXXX-Y', 'auto', {
  'clientId': getClientIdFromUrl()
});

If a client ID already exists on the destination domain, this method will overwrite it.

Detecting URL sharing

A potential problem with passing the client ID in a URL is that users share URLs and it's possible a user will share a URL that contains a client ID belonging to someone else.

One way to avoid this problem is to append a timestamp to the client ID. This allows you to detect when the URL was originally created, and if too much time has passed, consider the client ID invalid. In addition to a timestamp, you can append the user agent string or other browser or device-specific metadata. Then on the destination domain, if the metadata does not match, you'll know the client ID originated from someone else.

Ignoring self-referrals

A new referral campaign will be created whenever the document referrer of a page comes from a hostname that does not match any of the entries in the Referral Exclusion list for your property.

By default, the Referral Exclusion list includes only the domain that you provided when the property was first created. To prevent new referral campaigns from being generated when users navigate across domains, you must add an entry for each domain you wish to measure in the Referral Exclusion list.

Iframes

The technique described above requires JavaScript code that runs after analytics.js loads. Since <iframe> elements typically exist on the page prior to analytics.js being loaded, appending the client ID to the URL in the iframe's source parameter is often not an option.

To solve this problem you can configure the page inside the iframe to delay creating its tracker until after it receives the client ID data from the parent page. And on the parent page you configure it to send the client ID to the iframe page using postMessage.

Here's an example of the parent page code on source.com:

 

<iframe id="destination-frame" src="https://destination.com"></iframe>

<script>
ga('create', 'UA-XXXXX-Y', 'auto');
ga(function(tracker) {
  // Gets the client ID of the default tracker.
  var clientId = tracker.get('clientId');

  // Gets a reference to the window object of the destionation iframe.
  var frameWindow = document.getElementById('destination-frame').contentWindow;

  // Sends the client ID to the window inside the destination frame.
  frameWindow.postMessage(clientId, 'https://destination.com');
});
</script>

And here's the code that would receive the message in the iframe hosted on destination.com:

 

window.addEventListener('message', function(event) {
  // Ignores messages from untrusted domains.
  if (event.origin != 'https://destination.com') return;

  ga('create', 'UA-XXXXX-Y', 'auto', {
    clientId: event.data
  });
});

It's possible that analytics.js will fail to load on the parent page and then the page in the iframe will never receive the client ID. How you handle this case depends on how important it is that the client IDs match.

If you only want to capture data when you know the client IDs are the same, the above code is sufficient. If you want to capture data on the page in the frame regardless of whether it receives the client ID from the parent page, you'll have to add a fallback.

The following code uses a timeout on the page in the iframe to handle the case where the parent page is slow or fails to send the client ID:

 

// Stores whether or not the tracker has been created.
var trackerCreated = false;

function createTracker(opt_clientId) {
  if (!trackerCreated) {
    var fields = {};
    if (opt_clientId) {
      fields.clientId = opt_clientId;
    }

    ga('create', 'UA-XXXXX-Y', 'auto', fields);
    trackerCreated = true;
  }
}


window.addEventListener('message', function(event) {
  // Ignores messages from untrusted domains.
  if (event.origin != 'https://destination.com') return;

  // Creates the tracker with the data from the parent page.
  createTracker(event.data);
});


// Waits for three seconds to receive the client ID from the parent page.
// If that doesn't happen, it creates the tracker as normal.
setTimeout(createTracker, 3000);

 

Custom Dimensions and Metrics

This guide describes how to send custom dimensions and metrics using analytics.js.

Overview

Custom dimensions and metrics are a powerful way to send custom data to Google Analytics. Web developers can use custom dimensions and metrics to segment and measure differences between logged in and logged out users, authors of pages, levels in games, or any other business data you have on a page.

For a complete overview on how this feature works, read the Custom Dimensions and Metrics Feature Reference.

You send custom dimension and metric data using either one or both of the following values:

Field NameValue TypeRequiredDescription
dimension[0-9]+textNoThe dimension index. Each custom dimension has an associated index.There is a maximum of 20 custom dimensions (200 for Analytics 360 accounts). The index suffix must be a positive integer greater than 0 (e.g. dimension3).
metric[0-9]+integerNoThe metric index. Each custom metric has an associated index. There is a maximum of 20 custom metrics (200 for Analytics 360 accounts). The index suffix must be a positive integer greater than 0 (e.g. metric5).

Implementation

You must first configure a custom dimension or metric through the Google Analytics Management Interface. Once configured, the custom dimension or metric will be assigned a unique index that identifies and differentiates one custom dimension or metric from another. You then use the index in the analytics.js library to send data for a particular custom dimension or metric.

To learn how to configure a custom dimension or metric, read Create and edit custom dimensions and metrics in the Google Analytics help center.

Sending Data

Custom dimension or metric data may only be sent with an existing hit. For example, to send a custom dimension for a pageview type hit with the index 15, you would use:

 

ga('send', 'pageview', {
  'dimension15':  'My Custom Dimension'
});

To send a custom metric for an event type hit with the index 18, you would use:

 

ga('send', 'event', 'category', 'action', {
  'metric18': 8000
});

If the custom metric is configured to have a currency type, you can send decimal values:

 

ga('send', 'event', 'category', 'action', {
  'metric19': 24.99
});

In some cases, you might want to send a custom dimension or metric with all the hits on a given page (or for the lifetime of the tracker object). In this case, you can set the custom dimension or metrics using the set command:

 

ga('set', 'dimension5', 'custom data');

To set values for both a dimension and metric, you can use:

 

ga('set', {
  'dimension5': 'custom dimension data',
  'metric5': 'custom metric data'
});

Read the Custom Dimensions and Metrics Section in the Field Reference document for the specific format of how to send this data.

Example

A fantastic example of when to use custom dimensions is if you had a content based site with many authors. As an analyst, you might want to understand which authors have the most popular content. To answer this question, you could view a report that compares pageviews by author. Although author data is not available by default in Google Analytics, you can send this data as a custom dimension with each pageview being tracked.

The first step in the solution is to configure a new custom dimension in the management interface. The name should be author and the scope will be of type hit. Once configured, the new custom dimension will be assigned an index. For this example, let's say the index is 5.

Now that the author custom dimension has been configured and assigned an index, it can be used with the analytics.js library to send author data as a custom dimension. For example, if your page is written in PHP, the actual author of the page will probably be stored in a PHP variable like $author. In your PHP template, you can use this author variable to pass the author value to the custom dimension:

 

ga('send', 'pageview', {
  'dimension5': '<?=$author?>'
});

 

Renaming the ga object

In some cases you'd like to add analytics.js to your page, but the ga variable is already being used for something else. To deal with this, analytics.js provides a mechanism for renaming the global ga object.

Renaming the global object in the tracking snippet

The JavaScript tracking snippet allows you to rename the global ga object by changing the final parameter passed to the minified function. You'll also need to update all invocations of the command queue from ga() to whatever name you choose.

For example, if you wanted to rename the ga object to analytics, you could change the tracking snippet as follows:

 

<!-- 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','analytics');

analytics('create', 'UA-XXXXX-Y', 'auto');
analytics('send', 'pageview');
</script>
<!-- End Google Analytics -->

Manually renaming the global object

Renaming the global object works because analytics.js, when it loads, looks for a string stored on a global variable called GoogleAnalyticsObject. If it finds that variable, it uses the string name as the new name for the global command queue.

If you're loading analytics.js and not using the tracking snippet, you can still rename the global object by setting the name you want to use on the variable GoogleAnalyticsObject prior to loading the analytics.js library.

For example, if you're using jQuery's $.getScript method to load analytics.js, you could rename the global object with the following code:

 

<script>
// Instructs analytics.js to use the name `analytics`.
window.GoogleAnalyticsObject = 'analytics';

// Uses jQuery to load analytics.js instead of the tracking snippet.
$.getScript('//www.google-analytics.com/analytics.js', function() {

  // Creates a tracker and sends a pageview using the renamed command queue.
  analytics('create', 'UA-12345-1', 'auto');
  analytics('send', 'pageview');
});
</script>

The alternative async tracking snippet

Unlike the standard JavaScript tracking snippet, the alternative async tracking snippet does not offer default support for renaming the global ga object.

However, using the technique described above, you can rename the global ga object and still get all the preloading benefits of the alternative async tracking snippet.

The following modified version of the alternative async tracking snippet sets the GoogleAnalyticsObject variable to analytics and renames all instances of ga to analytics as well:

 

<!-- Google Analytics -->
<script>

// Instructs analytics.js to use the name `analytics`.
window.GoogleAnalyticsObject = 'analytics';

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

// Sets the time (as an integer) this tag was executed.
// Used for timing hits.
analytics.l = +new Date;

// Creates a default tracker with automatic cookie domain configuration.
analytics('create', 'UA-12345-1', 'auto');

// Sends a pageview hit from the tracker just created.
analytics('send', 'pageview');
</script>

<!-- Sets the `async` attribute to load the script asynchronously. -->
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->

 

Writing Plugins

Plugins are scripts that enhance the functionality of analytics.js to help solve problems and aid in measuring user interaction. This guide describes the process of writing your own analytics.js plugins. For information about how to use analytics.js plugins in your own implementations, see Using plugins.

Defining a plugin

Plugins are defined via the provide command, which must be invoked with the name of the plugin as the first argument followed by the plugin's constructor function. When the provide command is run, it registers the plugin to be used with the ga() command queue.

The plugin constructor

The following is the most basic example of an analytics.js plugin:

 

// Defines the plugin constructor.
function MyPlugin() {
  console.log('myplugin has been required...');
}

// Registers the plugin for use.
ga('provide', 'myplugin', MyPlugin);

Plugins need to function correctly even in cases where the global ga object has been renamed, so if you're writing a plugin for third-party use, you should include a check to see if the GoogleAnalyticsObject variable has been set to a string other than 'ga'. The following providePlugin function does this:

 

// Provides a plugin name and constructor function to analytics.js. This
// function works even if the site has customized the ga global identifier.
function providePlugin(pluginName, pluginConstructor) {
  var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
  if (typeof ga == 'function') {
    ga('provide', pluginName, pluginConstructor);
  }
}

Configuring Plugin Instances

When the ga() command queue executes a require command, it instantiates a new object using the new operator on the provide plugin's constructor function. The constructor is passed the tracker object as its first argument, and any configuration options passed to the require command as its second argument.

Consider the following require command added to the JavaScript tracking snippet:

 

ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'localHitSender', {path: '/log', debug: true});
ga('send', 'pageview');

And the localHitSender code:

 

function LocalHitSender(tracker, config) {
  this.path = config.path;
  this.debug = config.debug;
  if (this.debug) {
    console.log('localHitSender enabled for path: ' + this.path);
    console.log('on tracker: ' + tracker.get('name'));
  }
}

providePlugin('localHitSender', LocalHitSender);

When the require command is run, the following will be logged to the console (note that the name of the default tracker is "t0"):

 

// localHitSender enabled for path: /log
// on tracker: t0

Defining Plugin Methods

Plugins can expose their own methods which can be invoked using the ga command queue syntax:

 

ga('[trackerName.]pluginName:methodName', ...args);

where trackerName is optional and methodName corresponds to the name of a function on the plugin constructors prototype. If methodName does not exist on the plugin or the plugin does not exist, an error will occur.

Example plugin method calls:

 

// Execute the 'doStuff' method using the 'myplugin' plugin.
ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'myplugin');
ga('myplugin:doStuff');

// Execute the 'setEnabled' method of the 'hitCopy' plugin on tracker 't3'.
ga('create', 'UA-XXXXX-Y', 'auto', {name: 't3'});
ga('t3.require', 'hitcopy');
ga('t3.hitcopy:setEnabled', false);

Example plugin method definitions:

 

// myplugin constructor.
var MyPlugin = function(tracker) {
};

// myplugin:doStuff method definition.
MyPlugin.prototype.doStuff = function() {
  alert('doStuff method called!');
};

// hitcopy plugin.
var HitCopy = function(tracker) {
};

// hitcopy:setEnabled method definition.
HitCopy.prototype.setEnabled = function(isEnabled) {
  this.isEnabled = isEnabled;
}:

Loading plugins

Plugins are typically loaded from a separate JavaScript file or bundled together with your main application code.

 

<script async src="myplugin.js"></script>

Plugins do not necessarily need to be defined before they are required. Since analytics.js is loaded asynchronously and plugins are often also loaded asynchronously, the ga() command queue is built to handle this.

If the command queue receives a require command for a plugin that has not yet been provided, it will halt execution of the remaining items in the queue until the plugin is available.

The following code shows how the ga('require', 'myplugin') command is not actually executed until the ga('provide', 'myplugin', ...) command is encountered, three seconds later.

 

ga('require', 'myplugin');

function MyPlugin() {
  console.log('myplugin has been required...');
}

// Waits 3 second after running the `require`
// command before running the `provide` command.
setTimeout(function() {
  ga('provide', 'myplugin', MyPlugin);
}, 3000);

Important! While order of the require and provide commands is not important, they cannot be called before the JavaScript tracking snippet is run since they both reference to the global ga command queue function.

Examples

The following example plugin is designed to capture custom campaign values from a page's URL and pass them to the tracker. This plugin demonstrates how to define and register a plugin script, pass plugin configuration parameters, and define and call plugin methods.

 

// campaign-loader.js

function providePlugin(pluginName, pluginConstructor) {
  var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
  if (typeof ga == 'function') {
    ga('provide', pluginName, pluginConstructor);
  }
}

/**
 * Constructor for the campaignLoader plugin.
 */
var CampaignLoader = function(tracker, config) {
  this.tracker = tracker;
  this.nameParam = config.nameParam || 'name';
  this.sourceParam = config.sourceParam || 'source';
  this.mediumParam = config.mediumParam || 'medium';
  this.isDebug = config.debug;
};

/**
 * Loads campaign fields from the URL and updates the tracker.
 */
CampaignLoader.prototype.loadCampaignFields = function() {
  this.debugMessage('Loading custom campaign parameters');

  var nameValue = getUrlParam(this.nameParam);
  if (nameValue) {
    this.tracker.set('campaignName', nameValue);
    this.debugMessage('Loaded campaign name: ' + nameValue);
  }

  var sourceValue = getUrlParam(this.sourceParam);
  if (sourceValue) {
    this.tracker.set('campaignSource', sourceValue);
    this.debugMessage('Loaded campaign source: ' + sourceValue);
  }

  var mediumValue = getUrlParam(this.mediumParam);
  if (mediumValue) {
    this.tracker.set('campaignMedium', mediumValue);
    this.debugMessage('Loaded campaign medium: ' + mediumValue);
  }
};

/**
 * Enables / disables debug output.
 */
CampaignLoader.prototype.setDebug = function(enabled) {
  this.isDebug = enabled;
};

/**
 * Displays a debug message in the console, if debugging is enabled.
 */
CampaignLoader.prototype.debugMessage = function(message) {
  if (!this.isDebug) return;
  if (console) console.debug(message);
};

/**
 * Utility function to extract a URL parameter value.
 */
function getUrlParam(param) {
  var match = document.location.search.match('(?:\\?|&)' + param + '=([^&#]*)');
  return (match && match.length == 2) ? decodeURIComponent(match[1]) : '';
}

// Register the plugin.
providePlugin('campaignLoader', CampaignLoader);

The above code can be included into an HTML page as follows:

 

<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-XXXXX-Y', 'auto');
ga('require', 'campaignLoader', {
  debug: true,
  nameParam: 'cname',
  sourceParam: 'csrc',
  mediumParam: 'cmed'
});
ga('campaignLoader:loadCampaignFields');

ga('send', 'pageview');
</script>

<!--Note: plugin scripts must be included after the tracking snippet. -->
<script async src="campaign-loader.js"></script>

Autotrack plugins

The autotrack library is open source, available on GitHub, and includes several analytics.js plugins that aid in tracking common user interactions. Refer to the autotrack source code to get a better understanding of how plugins work.

Tasks

This guide describes tasks, an advanced feature used to customize how analytics.js validates, constructs, and sends measurement protocol requests.

Overview

Each time the send command is called, analytics.js executes a sequence of tasks to validate, construct, and send a measurement protocol request from the user's browser to Google Analytics. The following table describes each of these tasks, in the order they are executed:

Task NameDescription
customTaskBy default this task does nothing. Override it to provide custom behavior.
previewTaskAborts the request if the page is only being rendered to generate a 'Top Sites' thumbnail for Safari.
checkProtocolTaskAborts the request if the page protocol is not http or https.
validationTaskAborts the request if required fields are missing or invalid.
checkStorageTaskAborts the request if the tracker is configured to use cookies but the user's browser has cookies disabled.
historyImportTaskImports information from ga.js and urchin.js cookies to preserve visitor history when a site migrates to Universal Analytics.
samplerTaskSamples out visitors based on the sampleRate setting for this tracker.
buildHitTaskBuilds a measurement protocol request string and stores it in the hitPayload field.
sendHitTaskTransmits the measurement protocol request stored in the hitPayload field to Google Analytics servers.
timingTaskAutomatically generates a site speed timing hit based on the siteSpeedSampleRate setting for this tracker.
displayFeaturesTaskSends an additional hit if display features is enabled and a previous hit has not been sent within the timeout period set by the display features cookie (_gat).

Each of these tasks is implemented as a JavaScript function which takes a single model parameter as input. The model is a simple object that provides access to any of the fields defined in the Analytics.js Field Reference.

Tasks can be accessed or replaced using the standard tracker get and set methods. Using these methods, you may replace tasks with your own custom functions, or augment the existing functionality by chaining your custom functions to execute before or after an existing task.

Implementation

This section describes how to add new functionality to existing tasks, replace the built-in task functions with your own custom code, or disable a task function entirely.

Overriding a task

To override a task, you can set its value to a function that does something different. A common reason to override tasks is to stub functionality when testing your analytics.js implementations.

The following code replaces the sendHitTask with a function that logs the hit payload to the console:

 

ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'sendHitTask', function(model) {
  console.log(model.get('hitPayload'));
});

Note: The autotrack library makes use of this technique when testing its plugins. For example the eventTracker testoverrides the sendHitTask with code that checks to ensure the correct event fields are set.

Adding to a task

To insert new functionality you can chain your custom task function to execute before or after an existing task. In the example below, the sendHitTask is replaced with a custom task function that first calls the original sendHitTaskfunction to send the normal request beacon to google-analytics.com/collection, then executes custom code to send a copy of the measurement protocol request to a local server.

 

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

ga(function(tracker) {

  // Grab a reference to the default sendHitTask function.
  var originalSendHitTask = tracker.get('sendHitTask');

  // Modifies sendHitTask to send a copy of the request to a local server after
  // sending the normal request to www.google-analytics.com/collect.
  tracker.set('sendHitTask', function(model) {
    originalSendHitTask(model);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/localhits', true);
    xhr.send(model.get('hitPayload'));
  });
});

ga('send', 'pageview');

Aborting Task Processing

A task can abort the processing of subsequent tasks by throwing an exception. If the task throwing the exception executes before the sendHitTask, this has the effect of preventing the measurement protocol request from being sent to Google Analytics servers. In the example below, we abort the request whenever the user's browser contains a cookie named 'testing' with the value 'true'.

 

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

ga(function(tracker) {
  var originalBuildHitTask = tracker.get('buildHitTask');
  tracker.set('buildHitTask', function(model) {
    if (document.cookie.match(/testing=true/)) {
      throw 'Aborted tracking for test user.';
    }
    originalBuildHitTask(model);
  });
});

ga('send', 'pageview');

Disabling a Task

To disable any of the built-in task functions, replace it with null.

 

ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'checkProtocolTask', null); // Disables file protocol checking.
ga('send', 'pageview');

 

IP Anonymization

In some cases, you might need to anonymize the IP address of the hit sent to Google Analytics.

For all hits

To anonymize the IP address for all hits sent from a single tracker, use the set command to set the anonymizeIp field to true on the tracker:

 

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

For a single hit

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值