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 type | Child attribute | Description |
---|---|---|
addListener AddListenerObject | N/A | An object with the |
type | Child attribute of type | The argument indicating that you are using the |
filter | Child attribute of type | By setting a filter, you can define the type of events or category of events the handler is called for. |
type | Child attribute of type | The category of an event. Possible values: |
name | Child attribute of type | The name of the event type. The value can be |
handler | Child attribute of type | The function that is called when the event occurs. |
token | Child attribute of type | 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
});
NoteIf 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
initialized
Fires once the JavaScript API has been initialized.
Syntax
var initialized = function(initialized);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
initialized InitializedObject | N/A | This is the object passed to the handler function. Required. |
type | Child attribute of type | The category of an event. The value is |
name | Child attribute of type | 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
action.applied
Fires when some action (set of changes) has been applied.
Syntax
var actionApplied = function(actionAppliedEvent);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
actionAppliedEvent ActionAppliedEvent | N/A | The data relevant to the action.applied event. Required. |
type | Child attribute of type | The type of the event. Always |
name | Child attribute of type | The name of the event. Always |
data | Child attribute of type | Data about the event. Required. |
changes | Child attribute of type | List of changes that were attempted. |
type | Child attribute of type | Type of the change (for example, |
selector | Child attribute of type | (For visual element-based changes only) Selector chosen in the editor. |
attributes | Child attribute of type | Change-specific attributes, such as the HTML attribute to modify, and the modified value. |
type | Child attribute of type | String value for |
campaignId | Child attribute of type | ID of campaign the action belongs to. Required. |
pageId | Child attribute of type | ID of the page on which the action was executed. Required. |
experimentId | Child attribute of type | ID of experiment the action belongs to, or undefined if campaign action. |
variationId | Child attribute of type | 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.
NoteThe 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
activated
Fires each time the Optimizely Web Experimentation snippet activates.
Syntax
var activated = function(activated);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
activated ActivatedObject | N/A | This is the object passed to the handler function. Required. |
type | Child attribute of type | The category of an event. The value is |
name | Child attribute of type | The name of the event type. This is set to |
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
- specify changes to active Pages (see above), and
- 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
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 type | Child attribute | Description |
---|---|---|
campaignDecided CampaignDecidedObject | N/A | The data relevant to the |
type | Child attribute of type | The category of an event. The value is |
name | Child attribute of type | The name of the event type. This is set to |
data | Child attribute of type | Data associated to this event. You can use this object to determine which campaign a decision was made for. |
campaign | Child attribute of type | The complete campaign object. |
changes | Child attribute of type | 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. |
| Child attribute of type | You can specify additional properties of your choice. |
commitId | Child attribute of type | 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 | Child attribute of type | An array of experiments within the campaign. For AB tests, there is always one experiment. Personalization Campaigns can have more experiments. |
audienceIds | Child attribute of type | Representation of audience conditions for the experiment, including audience IDs and combinators. See audience_conditions for format. |
audienceName | Child attribute of type | Representation of name of audiences used in the experiment. |
id | Child attribute of type | The ID of the experiment. |
name | Child attribute of type | The name of the experiment. |
integrationSettings | Child attribute of type | 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. |
| Child attribute of type | You can specify additional properties of your choice. |
variations | Child attribute of type | The variations within an experiment. There are one or more variations in an experiment. |
actions | Child attribute of type | The actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation. |
pageId | Child attribute of type | The ID of the page where the action takes place. |
changes | Child attribute of type | An array of changes that have been set up for this page. |
| Child attribute of type | You can specify additional properties of your choice. |
commitId | Child attribute of type | 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 | Child attribute of type | An array of experiments within the campaign. For AB tests, there is always one experiment. Personalization Campaigns can have more experiments. |
audienceIds | Child attribute of type | Representation of audience conditions for the experiment, including Audience IDs and combinators. See audience_conditions for format. |
audienceName | Child attribute of type | Representation of name of audiences used in experiment. |
id | Child attribute of type | The ID of the experiment. |
name | Child attribute of type | The name of the experiment. |
integrationSettings | Child attribute of type | 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. |
| Child attribute of type | You can specify additional properties of your choice. |
variations | Child attribute of type | The variations within an experiment. There are one or more variations in an experiment. |
actions | Child attribute of type | The actions that are executed once a visitor gets bucketed in this variation. The actions describe the variation. |
pageId | Child attribute of type | The ID of the page where the action takes place. |
changes | Child attribute of type | An array of changes that have been set up for this page. |
| Child attribute of type | You can specify additional properties of your choice. |
id | Child attribute of type | The ID of the variation. |
name | Child attribute of type | The name of the variation. |
weightDistributions | Child attribute of type | Traffic allocation among the variations in the experiment. |
entityId | Child attribute of type | The ID of the variation that has the |
endOfRange | Child attribute of type | Each object in the array has a |
id | Child attribute of type | The ID of the campaign. |
name | Child attribute of type | The name of the campaign. |
holdback | Child attribute of type | 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 | Child attribute of type | The policy of a campaign indicates if the campaign is an AB test or a Personalization campaign. The possible values are: |
integrationSettings | Child attribute of type | An object that contains all the integration settings that are enabled for this campaign. |
| Child attribute of type | You can specify additional properties of your choice. |
pageIds | Child attribute of type | An array with the IDs of all the pages that are used within the campaign. |
decisionTicket | Child attribute of type | The decision ticket. |
audienceIds | Child attribute of type | An array of audiences the visitor qualified for at the time of the decision. |
bucketingId | Child attribute of type | Optimizely unique end user ID used to bucket the visitor. |
preferredVariationMap | Child attribute of type | Contains a map of experiment ID to variation ID. |
decision | Child attribute of type | The decision for this campaign. Required. |
campaignId | Child attribute of type | The ID of the campaign the visitor is bucketed in. |
experimentId | Child attribute of type | The ID of the experiment the visitor is bucketed in (if any). |
isCampaignHoldback | Child attribute of type | 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 | Child attribute of type | The ID of the variation the visitor is bucketed in (if any). |
reason | Child attribute of type | The reason the visitor was not bucketed into a variation, for examplee, "not eligible for any experiments". |
error | Child attribute of type | 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 | Child attribute of type | 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
pageActivated
Fires each time a page becomes active.
Syntax
var pageActivated = function(pageActivated);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
pageActivated PageActivatedObject | N/A | The data relevant to the |
type | Child attribute of type | The category of an event. The value is |
name | Child attribute of type | The name of the event type. This is set to |
data | Child attribute of type | Data associated to this event. You can use this object to determine which page has been activated. |
page | Child attribute of type | The complete page object. |
activationType | Child attribute of type | The trigger type that activates the page. |
apiName | Child attribute of type | A machine-readable name for the page. The |
category | Child attribute of type | 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 | Child attribute of type | Whether or not this page is automatically deactivated when its trigger fires and conditions are false. |
id | Child attribute of type | The page ID. |
staticConditions | Child attribute of type | The conditions that need to be true for the page to be activated. |
undoOnDeactivation | Child attribute of type | 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 | Child attribute of type | An array of the visual tags saved on a page. Read more about visual tags. |
category | Child attribute of type | A tag category that was selected upon creation of the tag. Some valid values for category are: "category", "subcategory", "title", "price", "other". |
locator | Child attribute of type | The logic/CSS selector indicating where a tag is located on the page. |
apiName | Child attribute of type | A machine-readable name for the tag. |
locatorType | Child attribute of type | 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
pageDeactivated
Fires each time a page is deactivated.
Syntax
var pageDeactivated = function(pageDeactivated);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
pageDeactivated PageDeactivatedObject | N/A | The data relevant to the |
type | Child attribute of type | The category of an event. The value is |
name | Child attribute of type | The name of the event type. This is set to |
data | Child attribute of type | Data associated to this event. You can use this object to determine which page has been activated. |
page | Child attribute of type | The complete page object. |
activationType | Child attribute of type | The trigger type that activates the page. |
apiName | Child attribute of type | A machine-readable name for the page. The |
category | Child attribute of type | 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 | Child attribute of type | Whether or not this page is automatically deactivated when its trigger fires and conditions are false. |
id | Child attribute of type | The page ID. |
staticConditions | Child attribute of type | The conditions that need to be true for the page to be activated. |
undoOnDeactivation | Child attribute of type | 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 | Child attribute of type | An array of the visual tags saved on a page. Read more about visual tags . |
category | Child attribute of type | A tag category that was selected upon creation of the tag. Some valid values for category are: "category", "subcategory", "title", "price", "other". |
locator | Child attribute of type | The logic/CSS selector indicating where a tag is located on the page. |
apiName | Child attribute of type | A machine-readable name for the tag. |
locatorType | Child attribute of type | 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
originsSynced
Fires when visitor data has been loaded from other origins.
Syntax
var originsSynced = function(originsSynced);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
originsSynced OriginsSyncedObject | N/A | The name and type of the |
type | Child attribute of type | The type of the event. The value is |
name | Child attribute of type | The name of the event. The value is |
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
trackEvent
Fires whenever a Web event has occurred.
Syntax
var trackEvent = function(trackEvent);
Parameters
Parameter and type | Child attribute | Description |
---|---|---|
trackEvent TrackEventObject | N/A | The data relevant to the |
type | Child attribute of type |
|
name | Child attribute of type |
|
data | Child attribute of type | Data associated to this event. You can use this object to determine which event was triggered. |
type | Child attribute of type | The type of the tracked event (for example, |
name | Child attribute of type | The name of the tracked event. |
apiName | Child attribute of type | The apiName of the tracked event. Note that for |
category | Child attribute of type | The category of the tracked event or page. |
metrics | Child attribute of type | Metrics attached to the event, if any. |
revenue | Child attribute of type | Revenue value associated with the event, if any. |
tags | Child attribute of type | 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.