Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideProduct feedbackGitHubNuGetDev CommunitySubmit a ticketLog In

Add listener

Listen to a snippet lifecycle event.

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 AddListenerObjectThe argument indicating that you are using the addListener function. Required.
filter
FilterObject
Child attribute of type AddListenerObjectBy 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 FilterObjectThe category of an event. Possible values: lifecycle and analytics. Required.
name
string
Child attribute of type FilterObjectThe name of the event type. The value can be initialized, applied, activated, campaignDecided, pageActivated, pageDeactivated, originsSynced, or trackEvent.
handler
function
Child attribute of type AddListenerObjectThe function that will be called when the event occurs.

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 will be 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.

You can listen to the following types of events:

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 InitializedObjectThe category of an event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type InitializedObjectThe 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 will have processed all window.optimizely.push API calls that were made before the snippet began to execute or during Project JavaScript.

window.optimizely.get will now be 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.

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 ActionAppliedEventThe type of the event. Always "action" for this event. Required.
name
string
Child attribute of type ActionAppliedEventThe name of the event. Always "applied" for this event. Required.
data
ActionAppliedEventData
Child attribute of type ActionAppliedEventData 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 ChangeDataType of the change (e.g., "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 ChangeDataChange-specific attributes, such as the HTML attribute to modify, and the modified value.
type
string or function or undefined
Child attribute of type ChangeDataString value for "insert_html", "insert_image", and "custom_css". Function to execute if "custom_code".
campaignId
string
Child attribute of type ActionAppliedEventID of campaign the action belongs to. Required.
pageId
string
Child attribute of type ActionAppliedEventID of the page on which the action was executed. Required.
experimentId
string or undefined
Child attribute of type ActionAppliedEventID of experiment the action belongs to, or undefined if campaign action.
variationId
string or undefined
Child attribute of type ActionAppliedEventID 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 ActivatedObjectThe category of an event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type ActivatedObjectThe 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:

  • Visitor ID.
  • Page states. A page will be 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 will also reactivate 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 CampaignDecidedObjectThe category of an event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type CampaignDecidedObjectThe name of the event type. This is set to campaignDecided.
data
CampaignEventData
Child attribute of type CampaignDecidedObjectData associated to this event. You can use this object to determine which campaign a decision was made for.
campaign
Campaign
Child attribute of type CampaignEventDataThe complete campaign object.
changes
array[Change]
Child attribute of type CampaignChanges 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 ChangeYou can specify additional properties of your choice.
commitId
string
Child attribute of type CampaignA 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 CampaignAn 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 ExperimentRepresentation of audience conditions for the experiment, including audience IDs and combinators. See audience_conditions for format.
audienceName
string
Child attribute of type ExperimentRepresentation of name of audience(s) used in the experiment.
id
string
Child attribute of type ExperimentThe ID of the experiment.
name
string
Child attribute of type ExperimentThe name of the experiment.
integrationSettings
IntegrationObject
Child attribute of type ExperimentAn 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 IntegrationObjectYou can specify additional properties of your choice.
variations
array[Variation]
Child attribute of type ExperimentThe variations within an experiment. There are one or more variations in an experiment.
actions
Action
Child attribute of type VariationThe actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation.
pageId
string
Child attribute of type ActionThe ID of the page where the action will take place.
changes
array[Change] or string
Child attribute of type ActionAn array of changes that have been set up for this page.
*
string or integer
Child attribute of type ChangeYou can specify additional properties of your choice.
commitId
string
Child attribute of type CampaignA 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 CampaignAn 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 ExperimentRepresentation of audience conditions for the experiment, including Audience IDs and combinators. See audience_conditions for format.
audienceName
string
Child attribute of type ExperimentRepresentation of name of audience(s) used in experiment.
id
string
Child attribute of type ExperimentThe ID of the experiment.
name
string
Child attribute of type ExperimentThe name of the experiment.
integrationSettings
IntegrationObject
Child attribute of type ExperimentAn 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 IntegrationObjectYou can specify additional properties of your choice.
variations
array[Variation]
Child attribute of type ExperimentThe variations within an experiment. There are one or more variations in an experiment.
actions
Action
Child attribute of type VariationThe actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation.
pageId
string
Child attribute of type ActionThe ID of the page where the action will take place.
changes
array[Change]
Child attribute of type ActionAn array of changes that have been set up for this page.
*
string or integer
Child attribute of type ChangeYou can specify additional properties of your choice.
id
string
Child attribute of type VariationThe ID of the variation.
name
string
Child attribute of type VariationThe name of the variation.
weightDistributions
null or array[WeightDistributionsObject]
Child attribute of type ExperimentTraffic allocation among the variations in the experiment.
entityId
string
Child attribute of type WeightDistributionsObjectThe ID of the variation that has the endOfRange value assigned to it.
endOfRange
integer
Child attribute of type WeightDistributionsObjectEach 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 CampaignThe ID of the campaign.
name
string
Child attribute of type CampaignThe name of the campaign.
holdback
integer
Child attribute of type CampaignThe 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 CampaignThe 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 CampaignAn object that contains all the integration settings that are enabled for this campaign.
*
string or integer
Child attribute of type IntegrationObjectYou can specify additional properties of your choice.
pageIds
array[string]
Child attribute of type CampaignAn array with the IDs of all the pages that are used within the campaign.
decisionTicket
DecisionTicketObject
Child attribute of type CampaignEventDataThe decision ticket.
audienceIds
array
Child attribute of type DecisionTicketObjectAn array of audiences the visitor qualified for at the time of the decision.
bucketingId
string
Child attribute of type DecisionTicketObjectOptimizely unique end user ID used to bucket the visitor.
preferredVariationMap
object
Child attribute of type DecisionTicketObjectContains a map of experiment ID to variation ID.
decision
DecisionObject
Child attribute of type CampaignEventDataThe decision for this campaign. Required.
campaignId
string
Child attribute of type DecisionObjectThe ID of the campaign the visitor is bucketed in.
experimentId
string
Child attribute of type DecisionObjectThe ID of the experiment the visitor is bucketed in (if any).
isCampaignHoldback
Boolean
Child attribute of type DecisionObjectProperty 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 DecisionObjectThe ID of the variation the visitor is bucketed in (if any).
reason
string
Child attribute of type DecisionObjectThe reason the visitor was not bucketed into a variation, e.g., "not eligible for any experiments".
error
Error
Child attribute of type DecisionObjectAny 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 CampaignEventDataThe 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 will attribute 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 PageActivatedObjectThe category of an event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type PageActivatedObjectThe name of the event type. This is set to pageActivated.
data
PageEventData
Child attribute of type PageActivatedObjectData associated to this event. You can use this object to determine which page has been activated.
page
Page
Child attribute of type PageEventDataThe complete page object.
activationType
string
Child attribute of type PageThe trigger type that activates the page.
apiName
string
Child attribute of type PageA 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 PageAn 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 PageWhether or not this page is automatically deactivated when its trigger fires and conditions are false.
id
string
Child attribute of type PageThe page ID.
staticConditions
array
Child attribute of type PageThe conditions that need to be true for the page to be activated.
undoOnDeactivation
Boolean
Child attribute of type PageWhether or not the changes for this page are undone when this page deactivates. Note that not all types of changes can be undone. Learn more.
tags
array[VisualTagObject]
Child attribute of type PageAn array of the visual tags saved on a page. Read more about visual tags.
category
string
Child attribute of type VisualTagObjectA 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 VisualTagObjectThe logic/CSS selector indicating where a tag is located on the page.
apiName
string
Child attribute of type VisualTagObjectA machine-readable name for the tag.
locatorType
string
Child attribute of type VisualTagObjectA 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 PageDeactivatedObjectThe category of an event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type PageDeactivatedObjectThe name of the event type. This is set to pageDeactivated.
data
PageEventData
Child attribute of type PageDeactivatedObjectData associated to this event. You can use this object to determine which page has been activated.
page
Page
Child attribute of type PageEventDataThe complete page object.
activationType
string
Child attribute of type PageThe trigger type that activates the page.
apiName
string
Child attribute of type PageA 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 PageAn 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 PageWhether or not this page is automatically deactivated when its trigger fires and conditions are false.
id
string
Child attribute of type PageThe page ID.
staticConditions
array
Child attribute of type PageThe conditions that need to be true for the page to be activated.
undoOnDeactivation
Boolean
Child attribute of type PageWhether or not the changes for this page are undone when this page deactivates. Note that not all types of changes can be undone. Learn more.
tags
array[VisualTagObject]
Child attribute of type PageAn array of the visual tags saved on a page. Read more about visual tags.
category
string
Child attribute of type VisualTagObjectA 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 VisualTagObjectThe logic/CSS selector indicating where a tag is located on the page.
apiName
string
Child attribute of type VisualTagObjectA machine-readable name for the tag.
locatorType
string
Child attribute of type VisualTagObjectA 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 OriginsSyncedObjectThe type of the event. The value will be lifecycle for this event. Required.
name
string
Child attribute of type OriginsSyncedObjectThe name of the event. The value will be 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 will continue until the page unloads, but you won't receive any more notifications.

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

For more information, see our article on 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 TrackEventObjectanalytics
name
string
Child attribute of type TrackEventObjecttrackEvent
data
TrackEventData
Child attribute of type TrackEventObjectData associated to this event. You can use this object to determine which event was triggered.
type
string
Child attribute of type TrackEventDataThe type of the tracked event (e.g., "custom" for custom events, "pageview" for page-activated events).
name
string
Child attribute of type TrackEventDataThe name of the tracked event.
apiName
string
Child attribute of type TrackEventDataThe apiName of the tracked event. Note that for "pageview" events, this is the api_name of the page.
category
string
Child attribute of type TrackEventDataThe category of the tracked event/page.
metrics
MetricData
Child attribute of type TrackEventDataMetrics attached to the event, if any.
revenue
number or undefined
Child attribute of type MetricDataRevenue value associated with the event, if any.
tags
Object
Child attribute of type TrackEventDataMap 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.