Optimizely X JavaScript API

Check out the JavaScript API migration guide if you are looking to migrate from Optimizely Classic to Optimizely X.

This is a full reference for the Optimizely X JavaScript API, including the Data Object and API Function Calls. With the JavaScript API, you can:

  • Track common user interactions
  • Read campaign, experiment and state information
  • Control the execution of Optimizely
  • Debug campaigns and experiments

Track common user interactions

The first step to getting started with Optimizely X Web is tracking the key pages, events, and tags on your site. While much of this implementation is possible in the visual editor, we also provide a set of JavaScript APIs for defining pages, tracking events, and adding tags on each for full flexibility.

These APIs are similar to the tracking calls in Optimizely Classic, but they use a new format for pushing data. To call these new APIs, you call optimizely.push with an object containing a type property and additional parameters. See the sections below for detailed examples.

Some Classic API calls like trackEvent will automatically be recognized by Optimizely X, but you need to implement the new API format to get access to new features like event tags for behavioral targeting. You don't need to reimplement event tracking if you've already set it up, but you can use the new API format to track additional tags for behavioral targeting (see below).

Usage

// Optimizely Classic format
window["optimizely"].push(['trackEvent', 'watchedVideo']);

// Optimizely X format
window["optimizely"].push({
  type: "event",
  eventName: "watchedVideo",
  tags: { // Additional metadata for targeting (optional)
    title: "Funny Cats",
    duration: 30,
  }
});

Event

Track custom events in Optimizely. The event eventName will be tracked and associated with the current visitor.

Syntax

window["optimizely"].push(event);
Parameters
event
Type: EventObject Required

This is an event object.

Example Call

window["optimizely"].push({
  "type": "event",
  "eventName": "watchedVideo",
  "tags": {
    "title": "Funny Cats",
    "duration": 30,
    "revenue": 5000
  }
});

Description

The event method captures visitor behavior and additional data. You can track clicks and pageviews in Optimizely without code, but this API call supports tracking other behaviors like watching a video. These events can be used for measuring the results of a campaign, or for determining an audience based on behavior. Learn more about events.

Page

The page method tracks the visitor's current context on a website. This context is used for both analytics ("track the number of views to the checkout page") and targeting ("run this experiment on the checkout page"). Learn more about pages.

Syntax

window["optimizely"].push(page);
Parameters
page
Type: PageObject Required

This is a page object.

Example Call

window["optimizely"].push({
  "type": "page",
  "pageName": "watchedVideo",
  "tags": {
    "category": "Kitchen",
    "subcategory": "Blenders",
    "price": 64999,
    "sku": 113757
  }
});

Description

The page method tracks the visitor's current context on a website. This context is used for both analytics ("track the number of views to the checkout page") and targeting ("run this experiment on the checkout page").

Specifically, pushing a page has two effects:

  • Optimizely will track a pageview event for this page, incrementing the count of views to that page in analytics and recording the event in the user's behavioral profile
  • Any campaigns targeted to this page will be activated

Pages can be created visually in Optimizely with URL targeting, but this API call allows you to manually activate a page. This allows full flexibility for sites with dynamic content or challenging URL patterns.

Page information is reset whenever the browser reloads.

Tags

Tags are contextual metadata about pages and events. They identify what a user is looking at, clicking on, or interacting with.

Syntax

window["optimizely"].push(tag);
Parameters
tag
Type: TagObject Required

This is an tag object.

Example Call

window["optimizely"].push({
  "type": "tags",
  "tags": {
    "category": "Kitchen",
    "subcategory": "Blenders",
    "price": 64999,
    "sku": 113757
  }
});

Description

Tags are contextual metadata about pages and events. They identify what a user is looking at, clicking on, or interacting with. For example, you can use tags to describe a product being purchased, an article being read, or a flight being booked. Learn more about tags.

There are three ways to capture this context:

  • Directly on an event, using the tags property.
  • Directly on a page, using the tags property. These tags will be sent along with any event that happens on that page.
  • Finally, you can use this tags method directly to add context without activating a page and tracking a pageview. This is equivalent to the previous option, but it can be used when pages are already being activated using URL targeting.

User

Use this API to record the user's values for any number of dimensions or custom attributes. The syntax is identical for both. Custom attributes can be used for audience targeting as well as results segmentation.

In order to use custom attributes for audience targeting and results segmentaton, you must first create the attribute in the Optimizely UI. The User API will allow you to use any API name to set attributes that have not yet been created, but those attribute values will not be available for audience targeting or segmentation. If you later create a custom attribute using that same API name, previously stored values will be made available for audience targeting and segmentation the next time the Optimizely client updates.

The values are saved in localStorage and are persisted across sessions, so you don't need to provide them again on future page loads.

Syntax

window["optimizely"].push(user);
Parameters
user
Type: UserObject Required

This is a user object.

Example Call

window["optimizely"].push({
  "type": "user",
  "attributes": {
    "123": "custom attribute value",
    "customAttributeApiName": "this is also a custom attribute value"
  }
});

Examples

Specifying a custom attribute by ID

You can specify a custom attribute by using its ID as the key for an entry in the attributes object. Once you have created a custom attribute in the Optimizely X UI, an ID will be generated and displayed under Audiences > Attributes.

Example code for Specifying a custom attribute by ID
window["optimizely"].push({
  type: "user",
  attributes: {
    123: "gold"
  }
});
Specifying a custom attribute by API name

You can specify a custom attribute by using its API name as the key for an entry in the attributes object. You provide the API name when creating a custom attribute in the Optimizely X UI under Audiences > Attributes.

Example code for Specifying a custom attribute by API name
window["optimizely"].push({
  type: "user",
  attributes: {
    frequentFlyerStatus: "gold"
  }
});
Unsetting a user's custom attribute value

If you to remove a custom attribute value that had previously been set for a user, you can do that by providing a value of null.

Example code for Unsetting a user's custom attribute value
window["optimizely"].push({
  type: "user",
  attributes: {
    frequentFlyerStatus: null
  }
});

Reading Optimizely data and state

The API has a optimizely.get function that gives you access to the data that you have saved in your project (Campaigns, Experiments, Pages, Events and Audiences). With this function you can also get information about the current state of Optimizely in the browser.

Usage

// Get the state of Optimizely campaigns and experiments
window["optimizely"].get("state");

Data

Returns an object exposing the static data fields. These fields are the same for all visitors on all page loads until you modify your project.

Note: optimizely.get("data") is a performance intensive operation; as such you should use it sparingly. For example, if you need to get multiple pieces of data in the same function, call it once and reuse that reference:

var data = optimizely.get('data');
var experiment = data.experiments[myExperimentId];
var firstAudience = data.audiences[experiment.audienceIds[0]];

Syntax

data = window["optimizely"].get("data");
Parameters
data
Type: string Required

The argument indicating to get data information

Return value
Type: StaticData

The object contains the fields of the objects you have created using the Optimizely UI or REST API.

Example Call

data = window["optimizely"].get("data");

Example Return Value

{
  "audiences": {
    "4728608810": {
      "conditions": ["and", ["or", ["or", {
        "value": "search",
        "type": "source_type",
        "name": null,
        "match": null
      }, {
        "value": "campaign",
        "type": "source_type",
        "name": null,
        "match": null
      }]]],
      "id": "6618392098",
      "name": "Search traffic"
    }
  },
  "events": {
    "4958230289": {
      "category": "other",
      "name": null,
      "eventType": "click",
      "apiName": "blog_clicks_hero_nav",
      "id": "4958230289",
      "eventFilter": {
        "filterType": ".hero-container",
        "selector": "target_selector"
      },
      "pageId": "4761512980"
    }
  },
  "campaign": {
    "6676370413": {
      "holdback": 500,
      "activation": {},
      "integrationSettings": {},
      "viewIds": ["6678290257"],
      "experiments": [{
        "weightDistributions": null,
        "audienceName": "Chrome users",
        "name": null,
        "bucketingStrategy": null,
        "variations": [{
          "id": "6626731852",
          "actions": [],
          "name": "Variation #1"
        }],
        "audienceIds": ["6672770135"],
        "changes": null,
        "id": "6666781105",
        "integrationSettings": null
      }],
      "id": "6676370413",
      "weightDistributions": null,
      "name": "Example personalization campaign",
      "commitId": "6667420425",
      "decisionMetadata": null,
      "policy": "ordered",
      "changes": null,
      "pageIds": ["6678290257"]
    }
  },
  "pages": {
    "6678290257": {
      "category": "other",
      "staticConditions": ["and", ["or", {
        "type": "url",
        "value": "https://developers.optimizely.com/",
        "match": "simple"
      }]],
      "name": "Homepage",
      "tags": [{
        "category": "other",
        "locator": ".push-quad > a:nth-of-type(1)",
        "valueType": "string",
        "locatorType": "css_selector",
        "apiName": "view_docs_button"
      }],
      "apiName": "homepage",
      "id": "6678290257"
    }
  },
  "experiments": {
    "6661191859": {
      "weightDistributions": [{
        "entityId": "6665951608",
        "endOfRange": 5000
      }, {
        "entityId": "6670551924",
        "endOfRange": 10000
      }],
      "audienceName": "Everyone else",
      "name": null,
      "bucketingStrategy": null,
      "variations": [{
        "id": "6665951608",
        "actions": [],
        "name": "Original"
      }, {
        "id": "6670551924",
        "actions": [{
          "viewId": "6678290257",
          "changes": [{
            "selector": ".flex-justified--center > div:nth-of-type(1) .push-double--top",
            "dependencies": [],
            "attributes": {
              "html": "Web "
            },
            "type": "attribute",
            "id": "4810EE32-D209-4EBD-A8DC-6CE245DA8B6B",
            "css": {}
          }],
          "pageId": "6678290257"
        }],
        "name": "Variation #1"
      }],
      "audienceIds": null,
      "changes": null,
      "id": "6661191859",
      "integrationSettings": null
    }
  },
  "variations": {
    "7600254716": {
      "id": "7600254716",
      "actions": [{
        "viewId": "7585662249",
        "changes": [{
          "selector": "h1",
          "dependencies": [],
          "attributes": {
            "html": "Develop with Optimizely! "
          },
          "type": "attribute",
          "id": "EE809A94-4044-4DD0-B387-D05D478ED702",
          "css": {}
        }],
        "pageId": "7585662249"
      }],
      "name": "Variation #1"
    }
  },
  "projectId": "6663270427",
  "accountId": "200607994",
  "revision": "2433",
  "dcpServiceId": "3383760141"
}

Description

A function to get the data object. The data object contains the fields of the objects you have created using the Optimizely UI or REST API. For example: if you create a new experiment using an Audience, Page and Event, than you can expect to find all of those objects in the data object that is returned from this function.

Visitor

Optimizely uses visitor attributes for targeting and segmentation. The visitor object contains all the attributes that can be used for targeting and segmentation.

Syntax

visitor = window["optimizely"].get("visitor");
Parameters
visitor
Type: string Required

The argument indicating to get visitor information

Return value
Type: VisitorData

The object contains all the attributes that can be used for targeting and segmentation.

Example Call

visitor = window["optimizely"].get("visitor");

Example Return Value

{
  "browserId": "gc",
  "browserVersion": "53.0.2785.143",
  "source_type": "referral",
  "visitorId": "oeu1476217818972r0.36434468013549726",
  "custom": {
    "7973492630": {
      "id": "7973492630",
      "value": "High Tech"
    },
    "7995780411": {
      "id": "7995780411",
      "value": "commercial 1"
    }
  }
}

State

Returns a module exposing several functions to access information about the current visitor's state.

Syntax

state = window["optimizely"].get("state");
Parameters
state
Type: string Required

The argument indicating to get the state object.

Return value
Type: StateObject

The object contains functions to get more information about the current state of Optimizely.

Example Call

state = window["optimizely"].get("state");

Example Return Value

state.getActivationId();
state.getActiveExperimentIds();
state.getCampaignStates(filters);
state.getExperimentStates(filters);
state.getPageStates(filters);
state.getRedirectInfo();
state.getVariationMap();
state.getDecisionString();
state.getDecisionObject();

Get all the campaigns and their current states.

Syntax

state.getCampaignStates(filter);
Parameters
filter
Type: CampaignFilterObject or CampaignFilterFunction

An object with fields to filter on.

Return value
Type: object[CampaignStateObject]

Returns an object. The object keys are campaign ids. The values describe the state of every campaign.

Example Call

state.getCampaignStates({
  "isActive": true
});

Example Return Value

{
  "6676370413": {
    "id": "6676370413",
    "campaignName": "Example personalization campaign",
    "experiment": {
      "id": "6666781105",
      "name": null
    },
    "variation": {
      "id": "6626731852",
      "name": "Variation #1"
    },
    "isActive": true,
    "visitorRedirected": false,
    "isInCampaignHoldback": false,
    "audiences": [{
      "id": "6672770135",
      "name": "Chrome users"
    }]
  }
}

Description

Get all the campaigns and their current states. The filter argument allows you to filter the campaigns. It is possible to filter using an object or with a function.

Examples

Filter with a function

Filter the campaigns with a filter function.

Example code for Filter with a function
var state = window["optimizely"].get("state");

state.getCampaignStates(function(campaignState) {
  return !!campaignState.isActive;
});

Get all the Experiments and their current states.

Syntax

state.getExperimentStates(filter);
Parameters
filter
Type: ExperimentFilterObject or ExperimentFilterFunction

An object with fields to filter on.

Return value
Type: object[ExperimentStateObject]

Returns an object. The object keys are Experiment ids. The values describe the state of every Experiment.

Example Call

state.getExperimentStates({
  "isActive": true
});

Example Return Value

{
  "6666781105": {
    "id": "6666781105",
    "experimentName": null,
    "variation": {
      "id": "6626731852",
      "name": "Variation #1"
    },
    "isActive": true,
    "visitorRedirected": false,
    "isInExperimentHoldback": false,
    "audiences": [{
      "id": "6672770135",
      "name": "Chrome users"
    }]
  }
}

Description

Get A/B Experiments and their current states (excludes Personalization Campaigns). The filter argument allows you to filter the Experiments. It is possible to filter using an object or with a function.

Examples

Filter with a function

Filter the Experiments with a filter function.

Example code for Filter with a function
var state = window["optimizely"].get("state");

// "Not variation #1"
state.getExperimentStates(function(expState) {
  return !expState.variation || expState.variation.name !== "Variation #1";
})
Filter with an Object

Filter the Experiments with a match object.

Example code for Filter with an Object
var state = window["optimizely"].get("state");

state.getExperimentStates({
  isActive: true
});

Get all the pages and their current states.

Syntax

state.getPageStates(filter);
Parameters
filter
Type: PageFilterObject

The argument indicating to get data information

Return value
Type: object[PageStateObject]

Returns an object. The object keys are page ids. The values describe the state of every page.

Example Call

state.getPageStates({
  "isActive": true
});

Example Return Value

{
  "6678290257": {
    "id": "6678290257",
    "name": "Homepage",
    "apiName": "homepage",
    "category": "other",
    "staticConditions": ["and", ["or", {
      "type": "url",
      "value": "https://developers.optimizely.com/",
      "match": "simple"
    }]],
    "tags": [{
      "category": "other",
      "locator": ".push-quad > a:nth-of-type(1)",
      "valueType": "string",
      "locatorType": "css_selector",
      "apiName": "view_docs_button"
    }],
    "isActive": true,
    "metadata": {
      "view_docs_button": "View Docs"
    }
  }
}

Description

Get all the pages and their current states. The filter argument allows you to filter the pages. It is possible to filter using an object or with a function.

Examples

Filter with a function

Filter the campaigns with a filter function.

Example code for Filter with a function
var state = window["optimizely"].get("state");

state.getCampaignStates(function(pageState) {
  return !!pageState.isActive;
});

Get a mapping from each Experiment the visitor has ever seen to its current corresponding Variation.

Syntax

state.getVariationMap();
Return value
Type: object[VariationIdName]

An object where the keys are the Experiment ids of every Experiment the visitor has ever seen and the values are objects with the name, ID, and index of the Variation a visitor saw for that Experiment.

Example Call

state.getVariationMap();

Example Return Value

{
  "6661191859": {
    "id": "6670551924",
    "name": "Variation #1",
    "index": "1"
  }
}

Description

Get the mapping of all Experiments the visitor has ever seen to its current corresponding Variation. If the visitor is excluded from an Experiment due to traffic allocation, that Experiment will appear here and they will be bucketed into a Variation, but no visual changes will be applied.

Get an array of Experiment ids that are currently active on the page for the visitor.

Syntax

state.getActiveExperimentIds();
Return value
Type: array[integer]

An array of Experiment ids that are currently active on the page for the visitor.

Example Call

state.getActiveExperimentIds();

Example Return Value

["6661191859", "6666781105", "7555673865"]

Description

Get an array of Experiment ids that are currently active on the page for the visitor. If the visitor is excluded from an Experiment due to traffic allocation, the Experiment is considered active and they will be bucketed into a variation, but no visual changes will be applied. This situation is referred to as isInExperimentHoldback in the getExperimentStates API:

state.getExperimentStates()[{experiment_id}].isInExperimentHoldback

If a redirect variation was executed on the previous page, all the details of that experiment are accessible on the next page through the getRedirectInfo() function.

Syntax

state.getRedirectInfo();
Return value
Type: null or RedirectInfoObject

The object contains all the details about a redirect experiment that ran on the previous page.

Example Call

state.getRedirectInfo();

Example Return Value

{
  "experimentId": "7669390999",
  "variationId": "7662661235",
  "referrer": "https://www.google.com/"
}

Description

If a redirect variation was executed on the previous page, all the details of that experiment are accessible on the next page through the getRedirectInfo() function. Most analytics integrations use this information to correct referrer values.

Get a single string describing the campaign/experiment decision for a given campaign id.

Syntax

state.getDecisionString(config);
Parameters
config
Type: DecisionConfigObject Required

An object with configuration fields for the function

Return value
Type: string

For personalization campaign decisions, the string returned is a concatenation of the decision campaign, experiment, and variation names and ids, and holdback status. For A/B experiment decisions, the string returned is a concatenation of the decision experiment and variation names and ids. More details on expected string output.

Example Call

state.getDecisionString({
  "campaignId": "6676370413"
});

Example Return Value

"Example personalization campaign(6676370413):Example experiment(6666781105):Variation #1(6626731852):holdback"

Description

Get a single string describing the campaign/experiment decision for a given campaign id. This is often used to send campaign decision data to third party analytics integrations. This function takes a campaign id as a paramater; if the campaign in question is an AB test, make sure to still pass the campaign id, and this API will return only the information that is relevant to an A/B test. This makes it so that code consuming this API does not have to conditionalize on whether the decision is for an AB test or a personalization campaign.

Get an object with strings that describe the campaign/experiment decision for a given campaign id.

Syntax

state.getDecisionObject(config);
Parameters
config
Type: DecisionConfigObject Required

An object with configuration fields for the function

Return value
Type: GetDecisionObjectReturn

For personalization campaign decisions, the object returned contains values for the decision campaign, experiment, and variation names and ids, and holdback status. For A/B experiment decisions, the object returned contains values for the decision experiment and variation names and ids.

Example Call

state.getDecisionObject({
  "campaignId": "6676370413"
});

Example Return Value

{
  "campaign": "Shopping Cart (6676370413)",
  "experiment": "New Visitors (3243212353)",
  "variation": "Variation #1 (2344343121)",
  "holdback": false
}

Description

Get an object with strings that describe the campaign/experiment decision for a given campaign id. This is often used to send campaign decision data to third party analytics integrations. This function takes a campaign id as a paramater; if the campaign in question is an AB test, make sure to still pass the campaign id, and this API will return only the information that is relevant to an A/B test. This makes it so that code consuming this API does not have to conditionalize on whether the decision is for an AB test or a personalization campaign.

Visitor ID

Get the visitor id assigned by Optimizely.

Syntax

visitor_id = window["optimizely"].get("visitor_id");
Parameters
visitor_id
Type: string Required

The argument indicating to get visitor_id information

Return value
Type: VisitorIdsObject

The visitor ID object contains the visitor id assigned by Optimizely.

Example Call

visitor_id = window["optimizely"].get("visitor_id");

Example Return Value

{
  "randomId": "oeu1470101898133r0.04568111757824678"
}

Session

This API is deprecated, and will be removed after March 31, 2018. You can use the session_index field if you are looking to query for events from a particular session.

Get metadata for the current session.

Syntax

session = window["optimizely"].get("session");
Parameters
session
Type: string Required

The argument indicating to get session information

Return value
Type: SessionObject

The object containing session information.

Example Call

session = window["optimizely"].get("session");

Example Return Value

{
  "lastSessionTimestamp": 1476765927360,
  "sessionId": "b6d3c104-2057-408e-acfe-8ca554713d8f"
}

API functions

The Optimizely API has a lot of useful functions that can be used to control Optimizely. The functions can be split up in three types:

  • Functions have a global effect on Optimizely execution
  • Function that can be used to develop experiences (see also JavaScript execution)
  • Function that can be used to monitor what Optimizely is doing

Activate

Reactivate the client.

Syntax

window["optimizely"].push(activate);
Parameters
activate
Type: ActivateObject Required

An object with the type field set to activate.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "activate"
});

Description

Trigger a client activation

The client "activation" phase is where:

  • The visitor's IDs are read from cookies and if updated, data for that visitor is read from storage.
  • Immediately activated Pages are activated.
  • All other Pages are queued for activation.
  • Information about the environment, such as previous behavior, and data from third parties, is fetched.
  • A client activation event is tracked and new "activationId" created to distinguish from the prior activation.

In this way, calling the "activate" API is analogous to loading Optimizely in a new page view, but without requiring the page to be reloaded. This is especially useful in a Single Page App context, to enable the views of a Single Page App to emulate the behavior of Optimizely in multi-page websites.

Add Listener

Adds an event listener.

Syntax

window["optimizely"].push(addListener);
Parameters
addListener
Type: AddListenerObject Required

An object with the type field set to addListener.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "addListener",
  "filter": {
    "type": "lifecycle",
    "name": "initialized"
  },
  "handler": function(event) {
    console.log("Project " + window["optimizely"].get("data").projectId + " is initialized");
  }
});

Description

During the execution of the Optimizely snippet, a lot of events occur. For instance, when the JavaScript API is loaded, an initialized event happens. Whenever a decision is made about a campaign or experiment, a campaignDecided event happens. For every page object that is activated, a pageActivated event occurs. For all tracked events, a trackEvent occurs.

You can register a listener for all these types of events.

The API is initialized. get functions may be called, but may not return all state data.

Syntax

var initialized = function(initialized);
Parameters
initialized
Type: InitializedObject Required

This is the object passed to the handler function.

Example Call

var initialized = function(event) {
  // The API is fully functional after the initialized event.
  console.log("Project " + window["optimizely"].get("data").projectId + " is initialized");
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "initialized"
  },
  // Add the initialized function as a handler.
  handler: initialized
});

Description

The API is initialized. get functions may be called, but visitor-specific state data (such as that returned by get('visitor') and get('state').getCampaignStates()) may not have been determined yet.

Fired when some action (set of changes) has been applied. Details about the action can be found in the Event payload.

Syntax

var actionApplied = function(actionAppliedEvent);
Parameters
actionAppliedEvent
Type: ActionAppliedEvent Required

The data relevant to the action.applied event.

Example Call

var onActionApplied = function(event) {
  console.log("Applied action for Campaign:", event.data.campaignId);
}

window.optimizely.push({
  "type": "addListener",
  "filter": {
    "type": "action",
    "name": "applied"
  },
  "handler": onActionApplied
});

The Optimizely snippet is activated, and some "state" APIs can be used.

Syntax

var activated = function(activated);
Parameters
activated
Type: ActivatedObject Required

This is the object passed to the handler function.

Example Call

var activated = function(event) {
  // The Optimizely snippet has been activated.
  var visitorId = window.optimizely.get('visitor_id').randomId;
  console.log("The visitor ID is: " + visitorId);
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "activated"
  },
  // Add the activated function as a handler.
  handler: activated
});

Description

The Optimizely snippet is activated. This may happen immediately when the snippet loads, or after the "activate" API is called. You may use methods to query state about the visitor:

  1. Get Visitor ID using optimizely.get('visitor_id').randomId.
  2. All "Immediately activated" Pages using optimizely.get('state').getPageStates. For the purposes of this API, "immediately activated" encompasses all of:
  3. If a Decision can be made immediately for any Campaign triggered by those Pages, it can be queried using optimizely.get('state').getCampaignStates

A bucketing decision has been made for the visitor for a specific campaign.

Syntax

var campaignDecided = function(campaignDecided);
Parameters
campaignDecided
Type: CampaignDecidedObject Required

The data relevant to the campaignDecided event.

Example Call

var campaignDecided = function(event) {
  console.log("Visitor is now seeing variation " + event.data.decision.variationId + " of campaign " + event.data.campaign.name);
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "campaignDecided"
  },
  // Add the campaignDecided function as a handler.
  handler: campaignDecided
});

Description

Every time a bucketing decision is made for a campaign, the campaignDecided happens. This event is useful if you are interested in tracking which variations a visitor has been bucketed in.

Note that any Optimizely events triggered via the handler function will be attributed to the campaign for which a decision was made.

The current url and activation conditions are met for a page.

Syntax

var pageActivated = function(pageActivated);
Parameters
pageActivated
Type: PageActivatedObject Required

The data relevant to the pageActivated event.

Example Call

var pageActivated = function(event) {
  console.log("The page " + event.data.page.name + " is now active");
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "pageActivated"
  },
  // Add the pageActivated function as a handler.
  handler: pageActivated
});

Description

In Optimizely, a page can be created based on URL and activation conditions. Every time Optimizely is activated on a page, all immediately activated pages are evaluated for their URL conditions. Pages with different activation types can be activated in a later phase of the client execution.

Visitor data from foreign origins has been loaded and synced.

Syntax

var originsSynced = function(originsSynced);
Parameters
originsSynced
Type: OriginsSyncedObject Required

The name and type of the originsSynced event.

Example Call

var originsSynced = function() {
  console.log("Cross-origin data is now synced.");
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "originsSynced"
  },
  // Add the originsSynced function as a handler.
  handler: originsSynced
});

Description

When optimizely activates, it will try to sync data for the current visitor Id from other domains that you have listed in your project settings. Events are shared asynchronously across origins, so events from different origins may not be available when optimizely first executes. After the originsSynced event, data from different origins should be available. For more information, see this article on cross-origin targeting.

An event occurred on the page.

Syntax

var trackEvent = function(trackEvent);
Parameters
trackEvent
Type: TrackEventObject Required

The data relevant to the trackEvent event.

Example Call

var trackEvent = function(event) {
  console.log("The event " + event.data.name + " was tracked");
};
window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "analytics",
    name: "trackEvent"
  },
  // Add the trackEvent function as a handler.
  handler: trackEvent
});

Description

When an event occurs on the current page, a trackEvent event happens. By listening to those events it is possible to send the same events to other systems where it is hared to track events. It is also possible to activate other campaigns once an event has occurred.

Behavior

You can use the behavior APIs if Optimizely X Web Personalization is enabled on your account.

If not, window.optimizely.get('behavior') will return undefined.

Syntax

behavior = window["optimizely"].get("behavior");
Parameters
behavior
Type: string Required
Return value
Type: BehaviorObject

Example Call

behavior = window["optimizely"].get("behavior");

Example Return Value

behavior.query(queryObject);

This API function runs a behavioral query over the events that have taken place on this device.

Currently, the API only considers events that took place before the most recent activation of the Optimizely snippet. You must reload the page if you want to query over events that took place on the current page load.

Syntax

behavior.query(queryObject);
Parameters
queryObject
Type: object Required

A behavioral query object.

Return value
Type: Object or Array or number or boolean or string

The result of the behavioral query.

Example Call

behavior.query("queryObject");

Examples

Page names

Obtain a list of page names, sorted by viewing frequency.

Example code for Page names
var behavior = window.optimizely.get('behavior');
var pageNames = behavior.query({
  "version": "0.2",
  "filter": [{
    "field": ["type"],
    "value": "pageview"
  }],
  "pick": {
    "field": ["name"]
  },
  "sort": [{
    "field": ["frequency"],
    "direction": "descending"
  }]
});

Bucket Visitor

Bucket the visitor into a given variation ID or index.

Syntax

window["optimizely"].push(bucketVisitor);
Parameters
bucketVisitor
Type: BucketObject Required

An object with the type field set to bucketVisitor.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "bucketVisitor",
  "experimentId": "6661191859",
  "variationIndex": 1
});

Description

Bucket the visitor into a given variation. Note: At this time, once an experiment --> variation mapping for a given visitor has been set, it won't be changed unless this method is used again. The function can be used by providing either a variationIndex or a variationId.

The association of the experiment to the variation you select won’t be changed unless the method is used again. However, the visitor could be bucketed into a different experiment next time they visit, if the api is not used again.

Cookie Domain

Instruct Optimizely to set its cookies on a specific subdomain instead of the default domain.

Syntax

window["optimizely"].push(cookieDomain);
Parameters
cookieDomain
Type: CookieDomainObject Required

An object with the type field set to cookieDomain.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "cookieDomain",
  "cookieDomain": "www.example.com"
});

Description

Instruct Optimizely to set its cookies on a specific subdomain instead of the default domain. You must call "setCookieDomain" prior to loading the Optimizely snippet. By default, Optimizely sets its cookies on the domain, in order to work across subdomains.

Cookie Expiration

Specify the number of days before the Optimizely visitor cookies will be set to expire.

Syntax

window["optimizely"].push(cookieExpiration);
Parameters
cookieExpiration
Type: CookieExpirationObject Required

An object with the type field set to cookieExpiration.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "cookieExpiration",
  "cookieExpirationDays": 365
});

Description

Specify the number of days before the Optimizely visitor cookies will be set to expire. You must call "setCookieExpiration" prior to loading the Optimizely snippet. The minimum number of days that can be set is 90 (approximately 3 months). For more information on how Optimizely uses cookies, visit our Learning Center.

Note: Some Optimizely cookies are re-set every time a visitor comes to the site, which means the expiration period set with this API call will be used each time the cookie is set.

Customer Profiles

You can use the dcp APIs if both of these conditions are true:

If either of the above does not apply, then window.optimizely.get('dcp') will return undefined.

Syntax

dcp = window["optimizely"].get("dcp");
Parameters
dcp
Type: string Required
Return value
Type: DCPObject

Example Call

dcp = window["optimizely"].get("dcp");

Example Return Value

dcp.getAttributeValue(attribute);
dcp.waitForAttributeValue(attribute);

This API function returns the visitor's value for a content-enabled profile attribute.

Syntax

dcp.getAttributeValue(datasourceId, attributeId, attributeName);
Parameters
datasourceId
Type: integer Required

Required.

attributeId
Type: integer

Required if attributeName is not provided.

attributeName
Type: string

Required if attributeId is not provided. Does not work if descriptive names are masked in the Optimizely client.

Return value
Type: number or boolean or string or Error

The uploaded attribute value, or undefined if any of the following are true:

  • A customer profile still needs to be uploaded for the current user.
  • A profile has been uploaded, but it does not include the desired attribute.
  • The Optimizely client is waiting for fresh data from the DCP service.

Note that this function throws an error if any of the following are true:

  • The specified attribute does not exist.
  • The attribute is not content-enabled.
  • The attribute is specified by name even though names are masked in the Optimizely client.

Example Call

dcp.getAttributeValue(datasourceId, attributeId, attributeName);

Examples

Specifying an attribute by ID

Get the value for a customer profile attribute.

Example code for Specifying an attribute by ID
var dcp = window.optimizely.get('dcp');
var attributeValue = dcp.getAttributeValue({
  datasourceId: 123,
  attributeId: 456
});
Specifying an attribute by name

Get the value for a customer profile attribute.

Example code for Specifying an attribute by name
var dcp = window.optimizely.get('dcp');
var attributeValue = dcp.getAttributeValue({
  datasourceId: 123,
  attributeName: 'Preferred Locale'
});

This API function returns a Promise that will be resolved as soon as Optimizely receives the visitor's value for a content-enabled profile attribute.

Syntax

dcp.waitForAttributeValue(datasourceId, attributeId, attributeName);
Parameters
datasourceId
Type: integer Required

Required.

attributeId
Type: integer

Required if attributeName is not provided.

attributeName
Type: string

Required if attributeId is not provided. Does not work if descriptive names are masked in the Optimizely client.

Return value
Type: Promise or Error

An ES6-style Promise that will be resolved with the uploaded attribute value, or with undefined if any of the following are true:

  • A customer profile still needs to be uploaded for the current user.
  • A profile has been uploaded, but it does not include the desired attribute.

If your campaign does not target a DCP Audience, then it is possible that profile data will not be fetched and the Promise will not be resolved.

Note that this function throws an error if any of the following are true:

  • The specified attribute does not exist.
  • The attribute is not content-enabled.
  • The attribute is specified by name even though names are masked in the Optimizely client.

Example Call

dcp.waitForAttributeValue(datasourceId, attributeId, attributeName);

Examples

Specifying an attribute by ID

Receive the value for a customer profile attribute once it has been fetched from the DCP server.

Example code for Specifying an attribute by ID
var dcp = window.optimizely.get('dcp');
dcp.waitForAttributeValue({
  datasourceId: 123,
  attributeId: 456
}).then(
  function(attributeValue) {
    ...
  }
);
Specifying an attribute by name

Receive the value for a customer profile attribute once it has been fetched from the DCP server.

Example code for Specifying an attribute by name
var dcp = window.optimizely.get('dcp');
dcp.waitForAttributeValue({
  datasourceId: 123,
  attributeName: 'Preferred Locale'
}).then(
  function(attributeValue) {
    ...
  }
);

Disable

Disable Optimizely entirely.

Syntax

window["optimizely"].push(disable);
Parameters
disable
Type: DisableObject Required

An object with the type field set to disable.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "disable"
});

Description

Disable Optimizely entirely. You must call disable prior to loading the Optimizely snippet.

You can also disable just Optimizely tracking calls from being made using the parameter scope: tracking.

Hold Events

Instuct the Optimizely snippet to hold and enqueue events.

Syntax

window["optimizely"].push(holdEvents);
Parameters
holdEvents
Type: HoldEventsObject Required

An object with the type field set to holdEvents.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "holdEvents"
});

Description

Use in conjunction with sendEvents for granular control over the timing of when the Optimizely snippet sends events to the logging endpoint.

The snippet must be configured to the use the /events logging endpoint in order to use this method. Learn more about how to enable this feature for your snippet.

Note: Failure to call sendEvents after using this method will effectively disable all tracking until the snippet is reinitialized. Use caution.

jQuery

The jQuery function returns a jQuery object if jQuery is bundled in Optimizely.

Syntax

jquery = window["optimizely"].get("jquery");
Parameters
jquery
Type: string Required

The argument indicating to get the jQuery object.

Return value
Type: jQueryObject

The jQuery object. You can learn more about the jQuery API here.

Example Call

jquery = window["optimizely"].get("jquery");

Description

Optimizely X, on its own, does not rely on jQuery. You only need to include jQuery in your project if you want to use it in implementing your campaigns and if you need to deliver it via the Optimizely snippet itself. You can find the option here: Project Settings page.

Log

Print execution logic to your browser's console.

Syntax

window["optimizely"].push(log);
Parameters
log
Type: LogObject Required

An object with the type field set to log.

Example Call

window["optimizely"].push({
  "type": "log",
  "level": "INFO"
});

Description

Tell Optimizely to output its log to the browser's console log (default is OFF).

You can also do this by using the query parameter optimizely_log={level}.

If you set the level to the currently-configured log level this function has no effect other than emitting a warning.

Opt Out

Opt a visitor out of Optimizely tracking.

Syntax

window["optimizely"].push(optOut);
Parameters
optOut
Type: OptOutObject Required

An object with the type field set to optOut.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "optOut",
  "isOptOut": false
});

Description

Opt a visitor out of Optimizely tracking. For example, you may want to opt visitors out of Optimizely tracking as part of your site's broader opt-out preferences.

Send Events

Instuct the Optimizely snippet to release queued events.

Syntax

window["optimizely"].push(sendEvents);
Parameters
sendEvents
Type: SendEventsObject Required

An object with the type field set to sendEvents.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "sendEvents"
});

Description

Use in conjunction with holdEvents for granular control over the timing of when the Optimizely snippet sends events to the logging endpoint.

The snippet must be configured to the use the /events logging endpoint in order to use this method. Learn more about how to enable this feature for your snippet.

Utilities

The utils function returns a utils object that includes useful functions for developing experiences.

Syntax

utils = window["optimizely"].get("utils");
Parameters
utils
Type: string Required

The argument indicating to get the utils object.

Return value
Type: UtilsObject

The utils object that contains a bunch of useful functions for developing experiences.

Example Call

utils = window["optimizely"].get("utils");

Example Return Value

utils.waitForElement(selector);
utils.observeSelector(selector, callback, options);
utils.poll(callback, delay);
utils.waitUntil(conditionFn);

Description

Optimizely X uses some common functions to deliver experiences. You can also use those functions to write your own custom experiences.

Returns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector.

Syntax

utils.waitForElement(selector);
Parameters
selector
Type: string Required

A css selector indicating the element to wait for.

Return value
Type: Promise

An ES6-style Promise that will be resolved with the matching element.

Example Call

utils.waitForElement("h2");

Description

Returns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector. This is commonly used to make adjustments to the element that you are waiting for when the promise is fulfilled.

Examples

Change the color of an element

Wait for an element to be loaded on the dom and change the color as soon as it has become available.

Example code for Change the color of an element
// Retrieve the utils library
var utils = window["optimizely"].get('utils');

// Wait for the footer element to appear in the DOM, then change the color
utils.waitForElement('.footer').then(function(footerElement) {
  footerElement.style.color = 'black';
});

Run a callback whenever an element changes.

Syntax

utils.observeSelector(selector, callback, options);
Parameters
selector
Type: string Required

A css selector indicating the element to wait for.

callback
Type: function Required

The function that will be executed when the element indicated by the selector changes. The first argument is the exact element that changed.

options
Type: ObserverOptions Required

A css selector indicating the element to wait for.

Return value
Type: function

A function that can be executed to unobserve selector.

Example Call

utils.observeSelector(".productPrice", function(element) {
  priceElement.style.fontSize = '30px';
  priceElement.style.color = 'red';
}, {
  "timeout": 6000,
  "once": true,
  "onTimeout": function() {
    console.log("Stopped observing");
  }
});

Description

This utility provides a subset of the functionality of a MutationObserver, allowing you to run a function whenever a DOM selector changes. Given a CSS selector and a callback, this function will invoke the supplied callback whenever a new element appears in the DOM matching the supplied selector.

A setInterval wrapper.

Syntax

utils.poll(callback, delay);
Parameters
callback
Type: function[Callback] Required

Function to be executed on the interval specified by delay.

delay
Type: integer Required

Milliseconds to wait in between each callback invocation.

Return value
Type: function

Returns a function that cancels the polling

Example Call

var utils = window["optimizely"].get("utils");

var cancelPolling = utils.poll(function() {
  timeRemaining = timeRemaining - 1000;

  // Update message based on how much time is remaining
  if (timeRemaining > 0) {
    var date = new Date(timeRemaining);
    headerElement.innerHTML = 'You have ' + date.getMinutes() + ':' + date.getSeconds() + ' before your reservation expires.';
  } else {
    headerElement.innerHTML = 'Your reservation has expired';
    cancelPolling();
  }
}, 1000);

Description

The poll function convenient wrapper around the setInterval function.

Wait until the provided function returns true.

Syntax

utils.waitUntil(conditionFunction);
Parameters
conditionFunction
Type: function Required

A function that executes synchronously and returns a truthy value when the condition is met.

Return value
Type: Promise

An ES6-style Promise that will be resolved with the matching element.

Example Call

utils.waitUntil(function() {
  var productsShownOnThePage = document.querySelectorAll('.product-listing');
  return productsShownOnThePage && productsShownOnThePage.length > 200;
});

Description

This utility accepts a function that returns a boolean value and returns a Promise that resolves when the supplied function returns true.

Examples

Warn after scrolling

Show the visitor an alert after the visitors has scrolled down a lot.

Example code for Warn after scrolling
// Retrieve the utils library
var utils = window["optimizely"].get('utils');

// We have infinite scroll enabled on the site. Wait until more than 200 products have been shown
// to prompt the user to try out our filter by color feature
utils.waitUntil(function() {
  var productsShownOnThePage = document.querySelectorAll('.product-listing');
  return productsShownOnThePage && productsShownOnThePage.length > 200;
}).then(function() {
  alert('Not finding what you\'re looking for? Try narrowing down your search using our new filter by color feature');
});

Wait For Origins

Wait for data to be received from other origins before Optimizely activates.

Syntax

window["optimizely"].push(waitForOriginSync);
Parameters
waitForOriginSync
Type: WaitForOriginObject Required

An object with the type field set to waitForOriginSync.

The other fields are the function arguments.

Example Call

window["optimizely"].push({
  "type": "waitForOriginSync",
  "canonicalOrigins": ["optimizely.com", "developers.optimizely.com"]
});

Description

You can use the waitForOriginSync API to make Optimizely wait for cross-origin data and sync before activating the snippet. When using this API, the visitor's ID will be set based on existing data, if any, from the specified origins, so that a single visitor will keep the same visitor ID, and relevant data, when moving back and forth across schemes or domains/TLDs. Since this will make the snippet wait for cross domain data for up to one second, it could cause a "flash" (if the page renders and an Experiment activates afterward, causing the snippet to apply visual changes). Because of this, we don't recommend using this API on pages that have above-the-fold visual Experiments. Click here for more information on cross-origin targeting.

Optimizely uses an iframe to persist localStorage from one website "origin" to another. Thus, anything that prevents the iframe from loading or initializing will cause waitForOriginSync to timeout and not emit the originsSynced event. There are three known ways this can happen.

  1. The origin setting in your optimizely.com account is set incorrectly.
  2. The user's browser blocks all iframes or iframes specifically from *.cdn.optimizely.com.
  3. The browser's privacy settings prevent setting or retrieving localStorage keys from iframe origins. (See below.)

Some browsers block cross-origin iframe localStorage if "third party cookies" are disabled. When a browser does this, the Optimizely iframe will not function when a user is on your website (because in this situation, the Optimizely iframe is from a separate website, i.e., a "third party" origin).