---
title: Add listener
slug: web-experimentation/api/82io-add-listener
docTags: 
createdAt: 2026-08-05T20:56:13.000Z
---

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

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

### Parameters

| Parameter and type                  | Child attribute                              | Description                                                                                                                                                                  |
| ----------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **addListener** *AddListenerObject* | N/A                                          | An 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](docId\:YQsL8i4LWzsOvWlzM53Od).                      |

### Example call

```javascript
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](docId\:lggNdsWeiw9HyDE7JSGsX). 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.

```javascript
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
});
```

:::hint{type="info"}
**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.

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

## `initialized`

Fires once the JavaScript API has been initialized.

### Syntax

```javascript
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** *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

```javascript
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 Web Experimentation snippet has processed all `window.optimizely.push` API calls that were made before the snippet began to execute or during [Project JavaScript](docId\:sVG-PHXNCgHp_N90jDQbx).

`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](docId\:f6yVHA1pGrQ6APkpc_3hA).

The snippet only initializes once per browser page load.

## `action.applied`

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

### Syntax

```javascript
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** *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*                            | 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

```javascript
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 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](docId\:u7NyuYQdFZ7CXPKxIQt1i), 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.

:::hint{type="info"}
**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](docId\:bhoKC5w_xxear_W4tpmMf).
:::

## `activated`

Fires each time the Optimizely Web Experimentation snippet activates.

### Syntax

```javascript
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** *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

```javascript
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 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](docId\:bhoKC5w_xxear_W4tpmMf) by
  - an [immediate](docId\:ql7lwhM3P9Ktrxtu58myr) trigger.
  - a [URL change](docId\:ql7lwhM3P9Ktrxtu58myr) or [DOM change](docId\:ql7lwhM3P9Ktrxtu58myr) trigger. (These triggers fire immediately during snippet activation, not just when the URL or DOM changes.)
  - a [callback](docId\:ql7lwhM3P9Ktrxtu58myr) 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](docId\:ql7lwhM3P9Ktrxtu58myr).
- Campaign states and experiment states. Campaigns and experiments apply changes to active pages and target audiences using data already available to the snippet, 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

```javascript
var campaignDecided = function(campaignDecided);
```

### Parameters

| Parameter and type                          | Child attribute                                      | Description                                                                                                                                                                                                                                                                |
| ------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **campaignDecided** *CampaignDecidedObject* | N/A                                                  | The 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*                         | 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*                     | 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*                     | 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*                      | 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* 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*                     | 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*                     | 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*                      | 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*                         | 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*   | 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*                         | 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 example, "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*                       | Child attribute of type `CampaignEventData`.         | The IDs of all the audiences in this campaign the visitor qualified for.                                                                                                                                                                                                   |

### Example call

```javascript
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 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](docId\:puGm9z4XkEG5PDkyaNmlA) 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](docId\:D8TcnvnT_dz1PDMcIQYyz) instead of using this API directly. Custom analytics integrations are easier to configure and, unlike this API, can be used to track [redirect](docId\:ib6NY46WEx3XMSyGNXjYA) decisions.

## `pageActivated`

Fires each time a page becomes active.

### Syntax

```javascript
var pageActivated = function(pageActivated);
```

### Parameters

| Parameter and type                      | Child attribute                                | Description                                                                                                                                                                                                     |
| --------------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **pageActivated** *PageActivatedObject* | N/A                                            | The 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](docId\:bhoKC5w_xxear_W4tpmMf).      |
| **tags** *array*                        | Child attribute of type `Page`.                | An array of the visual tags saved on a page. Read more about [visual tags](docId\:ZIaHsqJ6vlnxZUvy8RI00).                                                                                                       |
| **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

```javascript
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](docId\:SLF-avIbJk1qR9hh8NU8_) 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

```javascript
var pageDeactivated = function(pageDeactivated);
```

### Parameters

| Parameter and type                          | Child attribute                                  | Description                                                                                                                                                                                                          |
| ------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **pageDeactivated** *PageDeactivatedObject* | N/A                                              | The 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](docId\:bhoKC5w_xxear_W4tpmMf). |
| **tags** *array*                            | Child attribute of type `Page`.                  | An array of the visual tags saved on a page. Read more about [visual tags](docId\:ZIaHsqJ6vlnxZUvy8RI00).                                                                                                            |
| **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

```javascript
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](docId\:SLF-avIbJk1qR9hh8NU8_) 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](docId\:bhoKC5w_xxear_W4tpmMf) setting is on for this page).

## `originsSynced`

Fires when visitor data has been loaded from other origins.

### Syntax

```javascript
var originsSynced = function(originsSynced);
```

### Parameters

| Parameter and type                      | Child attribute                                | Description                                                               |
| --------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------- |
| **originsSynced** *OriginsSyncedObject* | N/A                                            | The 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

```javascript
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, 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 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](docId\:D4cK9MtLwo5SilACqb_sh).

## `trackEvent`

Fires whenever a Web Experimentation event has occurred.

### Syntax

```javascript
var trackEvent = function(trackEvent);
```

### Parameters

| Parameter and type                  | Child attribute                             | Description                                                                                                        |
| ----------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| **trackEvent** *TrackEventObject*   | N/A                                         | The 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

```javascript
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 [event](docId\:puGm9z4XkEG5PDkyaNmlA). 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](docId:8vTHKMfpmHSDLkMVrE1dy) or the [\`get('behavior') API\`](docId\:hwigB6Hgp15A7-HEpHwD9) if you have access to [Optimizely Personalization](https://www.optimizely.com/personalization/).
