JavaScript Method Reference

This page describes the anatomy of the major methods available to the JavaScript snippet. The basic tracking methods below are the building blocks of your Data Pipelines integration. They include Identify, Track, Page, Group, and Alias calls.

Identify

The identify method is how you link your users, and their actions, to a recognizable userId and traits. The Identify method follows the format below and includes the following options.

analytics.identify([userId], [traits], [options], [callback]);
ArgumentOptional/RequiredTypeDescription
userIdoptionalStringThe database ID for the user. If you don't know who the user is yet, you can omit the userId and just record traits. You can read more about identities in the identify reference.
traitsoptionalObjectA dictionary of traits you know about the user, like their email or name. You can read more about traits in the identify reference.
optionsoptionalObjectA dictionary of options. In most cases, options are just the integrations you want to enable or disable for the call. If you do not pass a traits object, pass an empty object (as an {}) before options
callbackoptionalFunctionA function executed after a short timeout, giving the browser time to make outbound requests first.

Identify calls and anonymous people

By default, we cache traits in the browser’s localStorage and attach them to subsequent identify calls. This means that you can make an identify call before someone has a userId, to store traits that you think will become meaningful later if or when you identify a person by their ID.

For example, you might call identify when someone signs up for alerts about a subject or a newsletter, but hasn’t yet created an account yet.

analytics.identify({
  favoriteBaseballTeam: 'san francisco giants',
  likes: ['baseball','hockey'],
  email: 'cool.person@example.com`
});

Then, when the user completes the sign up process, you could send the following event.

analytics.identify('12091906-01011992', {
  name: 'cool person',
});

The traits object for the second call will automatically pick up the email, likes, and favoriteBaseballTeam traits that you set in the first call!

Identify Callbacks

You can omit both traits and options, and pass a callback as the second argument.

analytics.identify('12091906-01011992', function(){
  // Do something after the identify request has been sent
  // Note: site-critical functionality should not depend on your analytics provider
});

Track

The Track method helps you record actions your users perform. You’ll find details about track calls in the track method payload.

The only required argument for the track method is an event name. In general, events contain some number of properties. Beyond that, you can also set options for the call (typically the integration destinations for the call), and a callback that you want to perform after the track call.

analytics.track('article_completed', {
  title: 'How to send a track event',
  course: 'Intro to Analytics',
},
{
    integrations: {
        "mixpanel": true,
        "salesforce": false
    }
});
analytics.track(event, [properties], [options], [callback]);
ArgumentOptional/RequiredTypeDescription
eventStringThe name of the event.
propertiesoptionalObjectA dictionary of [properties](/docs/api/cdp/#operation/track/) for the event. If the event name was 'Added to Cart', it might have properties like price and productType.
optionsoptionalObjectA dictionary of options. In most cases, options are just the integrations you want to enable or disable for the call. If you do not send traits, pass an empty object (as an {}) before options
callbackoptionalFunctionA function executed after a short timeout, giving the browser time to make outbound requests first.

The trackLink helper method attaches the track call as a handler to a link. It inserts a short, 300 ms timeout to give the track call more time to execute. You might do this to handle events in the event of a redirect that occurs before the track method could complete all requests.

var link = document.getElementById('free-trial-link');

analytics.trackLink(link, 'Clicked Free-Trial Link', {
  plan: 'Enterprise'
});
ArgumentOptional/RequiredTypeDescription
element(s)Element or ArrayDOM element that you want to bind to the track method. You can pass an array of elements or jQuery objects. But it must be an element. You cannot simply pass a CSS selector._
eventString or FunctionThe name of the event passed to the track method. You can also pass a function that returns a string that you want to use as the name of the track event.
propertiesoptionalObject or FunctionA dictionary of properties that you want to pass with the track method or a function that returns an object that you want to pass to the properties of the event.

Track Form

trackForm is a helper method that binds a track call to a form submission. It inserts a short, 300 ms timeout to give the track call more time to execute. You might do this to handle events in the event of a redirect that occurs before the track method could complete all requests.

var form = document.getElementById('signup-form');

analytics.trackForm(form, 'Signed Up', {
  plan: 'Premium',
  revenue: 99.00
});
ArgumentOptional/RequiredTypeDescription
form(s)Element or ArrayThe form element you want to track or an array of form elements/jQuery objects. You must provide elements; you cannot simply enter a CSS selector._
eventString or FunctionThe name of the event passed to the track method. You can also pass a function that returns a string that you want to use as the name of the track event.
propertiesoptionalObject or FunctionA dictionary of properties that you want to pass with the track method or a function that returns an object that you want to pass to the properties of the event.

Page

The Page method records page views on your website, along with optional extra information about the page a person visited.

Our JavaScript source automatically sends a page call on load. The JavaScript source instantiates libraries from your destinations and typically requires this call to be fired once per page to properly initialize your destinations.

A Page call is included by default as the final line in the JavaScript snippet. You can modify this page call.

analytics.page([category], [name], [properties], [options], [callback]);
ArgumentOptional/RequiredTypeDescription
categoryoptionalStringThe category of the page. This is useful for ecommerce-style cases where many pages might live under a category. If you pass only one string to page we assume that it's the page name. You must include a `name` to send a category.
nameoptionalStringThe name of the page.
propertiesoptionalObjectA dictionary of properties of the page. We automatically collect url, title, referrer, path, and search properties. The URL defaults to a canonical url if available, and falls back to document.location.href.
optionsoptionalObjectA dictionary of options. In most cases, options are just the integrations you want to enable or disable for the call. If you do not pass a traits object, pass an empty object (as an {}) before options
callbackoptionalFunctionA function executed after a short timeout, giving the browser time to make outbound requests first.

Default Page Properties

When you make a page call, we automatically add the title, url, path, referrer, and search properties. You can override these properties if you want—like if you use the JavaScript source in your single page app. Otherwise, if you send this call:

analytics.page('Docs');

We automatically add the following information:

analytics.page('Docs', {
  title: 'Customer.io Docs',
  url: 'https://customer.io/docs',
  path: '/docs',
  referrer: 'https://customer.io',
  search: '?utm_source=customerio&utm_medium=docs'
});

Group

The Group method associates an identified person with a group—like a company, organization, project, online class or any other collective noun you come up with for the same concept. In Customer.io Journeys, we call groups objectsNot to be confused with a JSON object, an object in Customer.io is a non-person entity that you can associate with one or more people—like a company, account, or online course. You can use objects to message people based on changes to their company, account, or course itinerary..

Group calls are useful for destinations where you maintain relationships between people and larger organizations, like in Customer.io! In Customer.io Journeys, you can store groups as objectsNot to be confused with a JSON object, an object in Customer.io is a non-person entity that you can associate with one or more people—like a company, account, or online course. You can use objects to message people based on changes to their company, account, or course itinerary., and trigger campaigns based on a person’s relationship to an object—like an account, online class, and so on.

Find more details about group, including the group payload, in our API spec.

The Group method follows the format below and contains the following fields.

analytics.group(groupId, [traits], [options], [callback]);
ArgumentOptional/RequiredTypeDescription
groupIdStringThe Group ID you want to associate with the identified person.
traitsoptionalObjectA dictionary of traits for the group. In Customer.io Journeys, we refer to these as attributesA key-value pair that you associate with a person or an object—like a person’s name, the date they were created in your workspace, or a company’s billing date etc. Use attributes to target people and personalize messages. Attributes are analogous to traits in Data Pipelines..
optionsoptionalObjectA dictionary of options. In most cases, options are just the integrations you want to enable or disable for the call. If you do not pass a traits object, pass an empty object (as an {}) before options
callbackoptionalFunctionA function executed after a short timeout, giving the browser time to make outbound requests first.

Example group call:

analytics.group('UNIVAC Working Group', {
  principles: ['Eckert', 'Mauchly'],
  site: 'Eckert–Mauchly Computer Corporation',
  statedGoals: 'Develop the first commercial computer',
  industry: 'Technology'
});

By default, group traits are cached in the browser’s local storage and attached to each subsequent group call, similar to how the identify method works.

Find more details about group including the group payload in the Group Spec.

Alias

The Alias method combines two previously unassociated user identities. Some destinations automatically reconcile profiles with different identifiers based on whether you send anonymousId, userId, or another trait that the destination expects to be unique. But for destinations that don’t, you may need to send alias requests to do this.

In general, you won’t need to use the alias call; we try to handle user identification gracefully, so that you don’t need to merge profiles. But you may need to send alias calls to manage user identities in some destinations.

For example, in Mixpanel it’s used to associate an anonymous user with an identified user once they sign up.

This is an advanced method. For now, you’ll only need to send alias calls to manage user identities successfully in Mixpanel. But we may add destinations in the future that’ll make use of this call.

analytics.alias(userId, [previousId], [options], [callback]);
ArgumentOptional/RequiredTypeDescription
userIdStringThe new user ID you want to set for a person.
previousIdoptionalStringThe user's previous userId. This defaults to the currently identified user's ID.
optionsoptionalObjectA dictionary of options. In most cases, options are just the integrations you want to enable or disable for the call.
callbackoptionalFunctionA function executed after a short timeout, giving the browser time to make outbound requests first.

The options object: setting destinations

The options object comes after traits or event properties in identify, track, page, group, and alias calls. It takes a single key called integrations and lets you determine the specific destinations that you want to send data to.

Each item in the integrations object is a boolean, where true sends data to the destination and false prevents data from going to the destination.

You can also set all to false, the call will only go to the destinations you explicitly set. If all is true or unset, we’ll send the call to all your destinations except destinations that you set to false.

analytics.identify('user_123', {
  email: 'cool.person@example.com',
  name: 'cool person'
}, {
  integrations: {
    'all': false,
    'Intercom': true,
    'Google Analytics': true
  }
});

 Use an empty object in place of empty traits or properties

Arguments in our JavaScript calls are positional: they’re read in order. Even if you don’t set traits or event properties, you’ll need to send an empty object, so we know where to find your options object and the integrations therein!

analytics.identify('user_123', {}, {
  integrations: {
    'all': false,
    'Intercom': true,
    'Google Analytics': true
  }
});

Load Options

You can modify the .load method in Analytics.js (the second line of the snippet) to take a second argument. If you pass an object with an integrations dictionary, then we’ll only load the integrations in that you set as true.

You can only call .load on page load, or reload (refresh). If you modify the .load method between page loads, it does not have any effect until the page reloads.

analytics.load('writekey', { integrations: { All: false, 'Google Analytics': true, 'Segment.io': true } })

This way, you can conditionally load integrations based on what customers opt into on your site. The example below shows how you might load only the tools that the user agreed to use. Learn more about the load method.

onConsentDialogClosed(function(consentedTools){
  analytics.load('writekey', { integrations: consentedTools })
})
Copied to clipboard!
  Contents
Is this page helpful?