Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
API Reference

Add listener

Use addListener to hook into Optimizely Web Experimentation lifecycle and analytics events from the snippet. This API gives you visibility into when Optimizely initializes, activates content, or assigns variations so you can react with custom code.

You can use the addListener API to listen for specific lifecycle events during the execution of the Optimizely Web Experimentation snippet.

Use this API to trigger custom code when important events occur, such as when the snippet initializes, activates a page, or assigns a visitor to a variation.

Listeners must be registered by pushing an addListener object onto the window["optimizely"] array.
If you want to remove a listener later, you must provide a token when adding the listener.

Use listeners to integrate Optimizely lifecycle events with your custom logic, analytics tools, or dynamic site behavior.

Syntax

window["optimizely"].push(addListener);

Parameters

Parameter and typeChild attributeDescription
addListener
AddListenerObject
N/AAn object with the type field set to addListener. The other fields are the function arguments. Required.
type
string
Child attribute of type AddListenerObject.The argument indicating that you are using the addListener function. Required.
filter
FilterObject
Child attribute of type AddListenerObject.By setting a filter, you can define the type of events or category of events the handler is called for.
type
string
Required
Child attribute of type FilterObject.The category of an event. Possible values: lifecycle and analytics. Required.
name
string
Child attribute of type FilterObject.The name of the event type. The value can be initialized, applied, activated, campaignDecided, pageActivated, pageDeactivated, originsSynced, or trackEvent.
handler
function
Child attribute of type AddListenerObject.The function that is called when the event occurs.
token
string
Child attribute of type AddListenerObject.A unique string that identifies the listener. Required if you want to remove the listener later. See Remove a listener.

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

Listen to a specific event from somewhere in the snippet's execution. For example, you can listen to the initialized event if you want to use the window.optimizely.get APIs as soon as they become available, or you can listen to the pageActivated event if you want to run code every time a page activates.

Your handler function is invoked for each applicable lifecycle event that occurs after the handler is registered. It is not retroactively invoked for events that may have occurred prior to handler registration.

Remove a listener

If you want to remove a listener after it is registered, you must provide a token when you add the listener. The token acts as an identifier that you can use to remove that specific listener later.

Add a listener with a token

When you add a listener, include a token field with a unique string value:

function onInitialized(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"
  },
  token: "UniqueListenerToken", // Replace with your token
  handler: onInitialized
});

📘

Note

If you do not provide a token when you add a listener, you cannot reference and remove that listener later.

Remove a listener with a token

When you want to remove the listener, call push again with the removeListener type and the same token.

window["optimizely"].push({
  type: "removeListener",
  token: "myUniqueListenerToken" // Replace with your token
});

initialized

Fires once the JavaScript API has been initialized.

Syntax

var initialized = function(initialized);

Parameters

Parameter and typeChild attributeDescription
initialized
InitializedObject
N/AThis is the object passed to the handler function. Required.
type
string
Child attribute of type InitializedObject.The category of an event. The value is lifecycle for this event. Required.
name
string
Child attribute of type InitializedObject.The name of the event type. This is set to initialized.

Example call

function onInitialized(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"
  },
  handler: onInitialized
});

Description

By this point, the Optimizely Web Experimentation snippet has processed all window.optimizely.push API calls that were made before the snippet began to execute or during Project JavaScript.

window.optimizely.get is now defined in addition to window.optimizely.push, although visitor-specific state data (such as that returned by get('visitor') and get('state').getCampaignStates()) may not have been determined yet. See Get.

The snippet only initializes once per browser page load.

action.applied

Fires when some action (set of changes) has been applied.

Syntax

var actionApplied = function(actionAppliedEvent);

Parameters

Parameter and typeChild attributeDescription
actionAppliedEvent
ActionAppliedEvent
N/AThe data relevant to the action.applied event. Required.
type
string
Child attribute of type ActionAppliedEvent.The type of the event. Always "action" for this event. Required.
name
string
Child attribute of type ActionAppliedEvent.The name of the event. Always "applied" for this event. Required.
data
ActionAppliedEventData
Child attribute of type ActionAppliedEvent.Data about the event. Required.
changes
array[ChangeData]
Child attribute of type array[ChangeData].List of changes that were attempted.
type
string
Child attribute of type ChangeData.Type of the change (for example, "attribute", "code").
selector
string or undefined
Child attribute of type ChangeData.(For visual element-based changes only) Selector chosen in the editor.
attributes
object or undefined
Child attribute of type ChangeData.Change-specific attributes, such as the HTML attribute to modify, and the modified value.
type
string or function or undefined
Child attribute of type ChangeData.String value for "insert_html", "insert_image", and "custom_css". Function to execute if "custom_code".
campaignId
string
Child attribute of type ActionAppliedEvent.ID of campaign the action belongs to. Required.
pageId
string
Child attribute of type ActionAppliedEvent.ID of the page on which the action was executed. Required.
experimentId
string or undefined
Child attribute of type ActionAppliedEvent.ID of experiment the action belongs to, or undefined if campaign action.
variationId
string or undefined
Child attribute of type ActionAppliedEvent.ID of variation the action belongs to, or undefined if campaign or experiment action.

Example call

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

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

Description

After the Optimizely Web Experimentation snippet has decided on a variation for a particular campaign or experiment, it delivers the experience as a set of "actions". Each action is specific to a variation (for most changes) or experiment (for Shared Code and Shared CSS, and may be specific to a page.

Use this lifecycle event to detect when actions have been applied. Your handler can inspect the event payload to distinguish between the various actions that may be applied during the current page load.

📘

Note

The snippet may reapply an action's changes after the corresponding lifecycle event has fired, if elements relevant to a particular change appear at different times rather than all at once. This is particularly likely if you are using Optimizely Web Experimentation on a dynamic website.

activated

Fires each time the Optimizely Web Experimentation snippet activates.

Syntax

var activated = function(activated);

Parameters

Parameter and typeChild attributeDescription
activated
ActivatedObject
N/AThis is the object passed to the handler function. Required.
type
string
Child attribute of type ActivatedObject.The category of an event. The value is lifecycle for this event. Required.
name
string
Child attribute of type ActivatedObject.The name of the event type. This is set to activated.

Example call

function onActivated(event) {
  var visitorId = window.optimizely.get('visitor_id').randomId;
  console.log("The visitor's ID is: " + visitorId);
}

window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "activated"
  },
  handler: onActivated
});

Description

At this point, the Optimizely Web Experimentation snippet has been activated, and you can query for visitor states such as the following:

  • Visitor ID.
  • Page states. A page is marked isActive if it was synchronously triggered
    by
    • an immediate trigger.
    • a URL change or DOM change trigger. (These triggers fire immediately during snippet activation, not just when the URL or DOM changes.)
    • a callback trigger, if its conditional activation code synchronously invokes the callback.
    • a manual trigger, if the corresponding JavaScript API was called before snippet activation and was found to have passing conditions.
  • Campaign states and experiment states, for campaigns and experiments that
    1. specify changes to active Pages (see above), and
    2. target audiences that the snippet was able to evaluate using data it already had on hand, without waiting for the browser to download additional data.

The snippet activates immediately upon snippet initialization, but also reactivates each time the activate API is called.

campaignDecided

Fires each time the visitor is assigned a variation (or none) for a campaign or experiment.

Syntax

var campaignDecided = function(campaignDecided);

Parameters

Parameter and typeChild attributeDescription
campaignDecided
CampaignDecidedObject
N/AThe data relevant to the campaignDecided event. Required.
type
string
Child attribute of type CampaignDecidedObject.The category of an event. The value is lifecycle for this event. Required.
name
string
Child attribute of type CampaignDecidedObject.The name of the event type. This is set to campaignDecided.
data
CampaignEventData
Child attribute of type CampaignDecidedObject.Data associated to this event. You can use this object to determine which campaign a decision was made for.
campaign
Campaign
Child attribute of type CampaignEventData.The complete campaign object.
changes
array[Change]
Child attribute of type Campaign.Changes on a campaign level. These changes are executed every time the campaign gets activated, regardless of the experiment and variation a visitor is assigned to.
*
string or integer
Child attribute of type Change.You can specify additional properties of your choice.
commitId
string
Child attribute of type Campaign.A new "commit" is made every time a campaign is published. The commit ID refers to the commit that was made. Every time a campaign is published, the commit ID changes.
experiments
array[Experiment]
Child attribute of type Campaign.An array of experiments within the campaign. For AB tests, there is always one experiment. Personalization Campaigns can have more experiments.
audienceIds
array[string,array]
Child attribute of type Experiment.Representation of audience conditions for the experiment, including audience IDs and combinators. See audience_conditions for format.
audienceName
string
Child attribute of type Experiment.Representation of name of audiences used in the experiment.
id
string
Child attribute of type Experiment.The ID of the experiment.
name
string
Child attribute of type Experiment.The name of the experiment.
integrationSettings
IntegrationObject
Child attribute of type Experiment.An object that contains all the integration settings that are enabled for this experiment. Each key in the object is mapped to a particular integration.
*
string or integer
Child attribute of type IntegrationObject.You can specify additional properties of your choice.
variations
array[Variation]
Child attribute of type Experiment.The variations within an experiment. There are one or more variations in an experiment.
actions
Action
Child attribute of type Variation.The actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation.
pageId
string
Child attribute of type Action.The ID of the page where the action takes place.
changes
array[Change] or string
Child attribute of type Action.An array of changes that have been set up for this page.
*
string or integer
Child attribute of type Change.You can specify additional properties of your choice.
commitId
string
Child attribute of type Campaign.A new "commit" is made every time a campaign is published. The commit ID refers to the commit that was made. Every time a campaign is published, the commit ID changes.
experiments
array[Experiment]
Child attribute of type Campaign.An array of experiments within the campaign. For AB tests, there is always one experiment. Personalization Campaigns can have more experiments.
audienceIds
array[string,array]
Child attribute of type Experiment.Representation of audience conditions for the experiment, including Audience IDs and combinators. See audience_conditions for format.
audienceName
string
Child attribute of type Experiment.Representation of name of audiences used in experiment.
id
string
Child attribute of type Experiment.The ID of the experiment.
name
string
Child attribute of type Experiment.The name of the experiment.
integrationSettings
IntegrationObject
Child attribute of type Experiment.An object that contains all the integration settings that are enabled for this experiment. Each key in the object is mapped to a particular integration.
*
string or integer
Child attribute of type IntegrationObject.You can specify additional properties of your choice.
variations
array[Variation]
Child attribute of type Experiment.The variations within an experiment. There are one or more variations in an experiment.
actions
Action
Child attribute of type Variation.The actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation.
pageId
string
Child attribute of type Action.The ID of the page where the action takes place.
changes
array[Change]
Child attribute of type Action.An array of changes that have been set up for this page.
*
string or integer
Child attribute of type Change.You can specify additional properties of your choice.
id
string
Child attribute of type Variation.The ID of the variation.
name
string
Child attribute of type Variation.The name of the variation.
weightDistributions
null or array[WeightDistributionsObject]
Child attribute of type Experiment.Traffic allocation among the variations in the experiment.
entityId
string
Child attribute of type WeightDistributionsObject.The ID of the variation that has the endOfRange value assigned to it.
endOfRange
integer
Child attribute of type WeightDistributionsObject.Each object in the array has a endOfRange value. The endOfRange of the current object minus the endOfRange object of the previous object is the traffic allocation assigned to the variation. The last object in the array always has a endOfRange value of 10000.
id
string
Child attribute of type Campaign.The ID of the campaign.
name
string
Child attribute of type Campaign.The name of the campaign.
holdback
integer
Child attribute of type Campaign.The holdback value on a campaign represents the percentage of visitors excluded from a campaign. If the holdback is set to 500, then 5% of all visitors are excluded from the campaign.
policy
string
Child attribute of type Campaign.The policy of a campaign indicates if the campaign is an AB test or a Personalization campaign. The possible values are:
"single_experiment": A normal AB test
"random": A Personalization campaign
integrationSettings
IntegrationObject
Child attribute of type Campaign.An object that contains all the integration settings that are enabled for this campaign.
*
string or integer
Child attribute of type IntegrationObject.You can specify additional properties of your choice.
pageIds
array[string]
Child attribute of type Campaign.An array with the IDs of all the pages that are used within the campaign.
decisionTicket
DecisionTicketObject
Child attribute of type CampaignEventData.The decision ticket.
audienceIds
array
Child attribute of type DecisionTicketObject.An array of audiences the visitor qualified for at the time of the decision.
bucketingId
string
Child attribute of type DecisionTicketObject.Optimizely unique end user ID used to bucket the visitor.
preferredVariationMap
object
Child attribute of type DecisionTicketObject.Contains a map of experiment ID to variation ID.
decision
DecisionObject
Child attribute of type CampaignEventData.The decision for this campaign. Required.
campaignId
string
Child attribute of type DecisionObject.The ID of the campaign the visitor is bucketed in.
experimentId
string
Child attribute of type DecisionObject.The ID of the experiment the visitor is bucketed in (if any).
isCampaignHoldback
Boolean
Child attribute of type DecisionObject.Property showing if a user has been included in the experiment based on the traffic allocation setting of the A/B experiment. For Personalization Campaigns, this property is based on the campaign holdback setting.
variationId
string
Child attribute of type DecisionObject.The ID of the variation the visitor is bucketed in (if any).
reason
string
Child attribute of type DecisionObject.The reason the visitor was not bucketed into a variation, for examplee, "not eligible for any experiments".
error
Error
Child attribute of type DecisionObject.Any uncaught error encountered in the process of evaluating the decision. This could be indicative of a problem and should be reported to Optimizely Web Experimentation Support.
audiences
array[integer]
Child attribute of type CampaignEventData.The IDs of all the audiences in this campaign the visitor qualified for.

Example call

function onCampaignDecided(event) {
  console.log("The 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"
  },
  handler: onCampaignDecided
});

Description

Each time the Optimizely Web Experimentation snippet activates a campaign or experiment, the snippet decides which variation (if any) to serve to the current visitor and then fires a campaignDecided event.

Any Web events triggered by your handler function attributes to the variation that the visitor has just been assigned to, in addition to previously served variations.

If you want to track decisions in an external analytics platform, we recommend that you create a custom analytics integration instead of using this API directly. Custom analytics integrations are easier to configure and, unlike this API, can be used to track redirect decisions.

pageActivated

Fires each time a page becomes active.

Syntax

var pageActivated = function(pageActivated);

Parameters

Parameter and typeChild attributeDescription
pageActivated
PageActivatedObject
N/AThe data relevant to the pageActivated event. Required.
type
string
Child attribute of type PageActivatedObject.The category of an event. The value is lifecycle for this event. Required.
name
string
Child attribute of type PageActivatedObject.The name of the event type. This is set to pageActivated.
data
PageEventData
Child attribute of type PageActivatedObject.Data associated to this event. You can use this object to determine which page has been activated.
page
Page
Child attribute of type PageEventData.The complete page object.
activationType
string
Child attribute of type Page.The trigger type that activates the page.
apiName
string
Child attribute of type Page.A machine-readable name for the page. The apiName value can be used in the page function to indicate which event has occurred.
category
string
Child attribute of type Page.An event category that was selected upon creation of the page. Some valid values for category are "added to cart", "saved", "shared", "searched", "purchased", "converted", "signed up", "subscribed", "other".
deactivationEnabled
Boolean
Child attribute of type Page.Whether or not this page is automatically deactivated when its trigger fires and conditions are false.
id
string
Child attribute of type Page.The page ID.
staticConditions
array
Child attribute of type Page.The conditions that need to be true for the page to be activated.
undoOnDeactivation
Boolean
Child attribute of type Page.Whether or not the changes for this page are undone when this page deactivates. Not all types of changes can be undone. See Dynamic websites and single-page applications.
tags
array[VisualTagObject]
Child attribute of type Page.An array of the visual tags saved on a page. Read more about visual tags.
category
string
Child attribute of type VisualTagObject.A tag category that was selected upon creation of the tag. Some valid values for category are: "category", "subcategory", "title", "price", "other".
locator
string
Child attribute of type VisualTagObject.The logic/CSS selector indicating where a tag is located on the page.
apiName
string
Child attribute of type VisualTagObject.A machine-readable name for the tag.
locatorType
string
Child attribute of type VisualTagObject.A enum that indicates if the locator is custom "javascript" or a "css_selector".

Example call

function onPageActivated(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"
  },
  handler: onPageActivated
});

Description

This event indicates when a page has become active.

In some cases, a page may activate during snippet activation, while in other cases activation may occur after snippet activation or not at all.

This event may fire before or after the snippet applies the page-specific changes specified by active variations.

pageDeactivated

Fires each time a page is deactivated.

Syntax

var pageDeactivated = function(pageDeactivated);

Parameters

Parameter and typeChild attributeDescription
pageDeactivated
PageDeactivatedObject
N/AThe data relevant to the pageDeactivated event. Required.
type
string
Child attribute of type PageDeactivatedObject.The category of an event. The value is lifecycle for this event. Required.
name
string
Child attribute of type PageDeactivatedObject.The name of the event type. This is set to pageDeactivated.
data
PageEventData
Child attribute of type PageDeactivatedObject.Data associated to this event. You can use this object to determine which page has been activated.
page
Page
Child attribute of type PageEventData.The complete page object.
activationType
string
Child attribute of type Page.The trigger type that activates the page.
apiName
string
Child attribute of type Page.A machine-readable name for the page. The apiName value can be used in the page function to indicate which event has occurred.
category
string
Child attribute of type Page.An event category that was selected upon creation of the page. Some valid values for category are "added to cart", "saved", "shared", "searched", "purchased", "converted", "signed up", "subscribed", "other".
deactivationEnabled
Boolean
Child attribute of type Page.Whether or not this page is automatically deactivated when its trigger fires and conditions are false.
id
string
Child attribute of type Page.The page ID.
staticConditions
array
Child attribute of type Page.The conditions that need to be true for the page to be activated.
undoOnDeactivation
Boolean
Child attribute of type Page.Whether or not the changes for this page are undone when this page deactivates. Note that not all types of changes can be undone. See Dynamic websites and single-page applications .
tags
array[VisualTagObject]
Child attribute of type Page.An array of the visual tags saved on a page. Read more about visual tags .
category
string
Child attribute of type VisualTagObject.A tag category that was selected upon creation of the tag. Some valid values for category are: "category", "subcategory", "title", "price", "other".
locator
string
Child attribute of type VisualTagObject.The logic/CSS selector indicating where a tag is located on the page.
apiName
string
Child attribute of type VisualTagObject.A machine-readable name for the tag.
locatorType
string
Child attribute of type VisualTagObject.A enum that indicates if the locator is custom "javascript" or a "css_selector".

Example call

function onPageDeactivated(event) {
  console.log("The Page " + event.data.page.name + " is no longer active");
}

window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "pageDeactivated"
  },
  handler: onPageDeactivated
});

Description

This event indicates when a page has been deactivated.

This event may fire before or after the snippet undoes the page-specific changes specified by active variations (if the Undo Changes setting is on for this page).

originsSynced

Fires when visitor data has been loaded from other origins.

Syntax

var originsSynced = function(originsSynced);

Parameters

Parameter and typeChild attributeDescription
originsSynced
OriginsSyncedObject
N/AThe name and type of the originsSynced event. Required.
type
string
Child attribute of type OriginsSyncedObject.The type of the event. The value is lifecycle for this event. Required.
name
string
Child attribute of type OriginsSyncedObject.The name of the event. The value is originsSynced for this event.

Example call

function onOriginsSynced() {
  console.log("Cross-origin data is now synced.");
}

window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "lifecycle",
    name: "originsSynced"
  },
  handler: onOriginsSynced
});

Description

During snippet initialization, Optimizely Web Experimentation tries to fetch data that has been saved for the current visitor ID under other origins' localStorage. Such data may exist if the visitor has previously used the current web browser to visit other origins on which you are running Optimizely Web Experimentation snippets.

This operation is asynchronous and may complete after the initial snippet activation (unless you use the waitForOriginSync API to delay that snippet activation). The originsSynced event indicates when this operation has succeeded or failed. You may want to wait for this event before executing logic that preferably sees data from all your origins.

After the originsSynced event, syncing continues until the page unloads, but you do not receive any more notifications.

As a security precaution, the snippet only syncs data between origins that you have listed in your account settings.

For information, see Cross-origin tracking in Optimizely Web Experimentation.

trackEvent

Fires whenever a Web event has occurred.

Syntax

var trackEvent = function(trackEvent);

Parameters

Parameter and typeChild attributeDescription
trackEvent
TrackEventObject
N/AThe data relevant to the trackEvent event. Required.
type
string
Child attribute of type TrackEventObject.analytics
name
string
Child attribute of type TrackEventObject.trackEvent
data
TrackEventData
Child attribute of type TrackEventObject.Data associated to this event. You can use this object to determine which event was triggered.
type
string
Child attribute of type TrackEventData.The type of the tracked event (for example, "custom" for custom events, "pageview" for page-activated events).
name
string
Child attribute of type TrackEventData.The name of the tracked event.
apiName
string
Child attribute of type TrackEventData.The apiName of the tracked event. Note that for "pageview" events, this is the api_name of the page.
category
string
Child attribute of type TrackEventData.The category of the tracked event or page.
metrics
MetricData
Child attribute of type TrackEventData.Metrics attached to the event, if any.
revenue
number or undefined
Child attribute of type MetricData.Revenue value associated with the event, if any.
tags
Object
Child attribute of type TrackEventData.Map of tag name to tag value.

Example call

function onTrackEvent(event) {
  console.log("The event " + event.data.name + " was tracked");
}

window["optimizely"] = window["optimizely"] || [];
window["optimizely"].push({
  type: "addListener",
  filter: {
    type: "analytics",
    name: "trackEvent"
  },
  handler: onTrackEvent
});

Description

The trackEvent lifecycle event is fired whenever the visitor triggers an Web event.

You can use this API if you want to track conversions in an external analytics platform.

You can also use this to manually activate a campaign or experiment after a particular event has occurred. For more complex targeting, you can use behavioral audiences or the get('behavior') API if you have access to Optimizely Web Personalization.