Skip to content

Web Experimentation JavaScript API Reference

intermediate

The window.optimizely JavaScript API lets you interact with Optimizely Web Experimentation from custom code on your website. You use it to activate experiments, send custom events, identify users, manage opt-out preferences, and control page activation.

All commands are sent through window.optimizely.push, which accepts an action object. The push-based pattern ensures commands are queued if the Optimizely snippet has not finished loading yet.

Every API call follows the same pattern:

window.optimizely = window.optimizely || [];
window.optimizely.push({
type: '<action_type>',
// ... action-specific parameters
});

Always initialize the array before pushing to avoid errors if the Optimizely snippet loads after your code.

Manually activates an experiment or campaign. Use this when the experiment’s activation conditions are set to “Manual” in the Optimizely app and you want to control exactly when the experiment runs.

activate
javascript
// Activate a specific campaign by ID
window.optimizely.push({
  type: 'activate',
  campaignId: '21938470052',
});

// Activate all experiments on the current page
window.optimizely.push({
  type: 'activate',
});
ParameterTypeRequiredDescription
campaignIdstringNoThe campaign ID to activate. If omitted, all eligible experiments on the current page are activated.
  • Your experiment targets a single-page application (SPA) where URL changes do not trigger a full page load.
  • You want to delay experiment activation until a specific element is visible or a user action occurs.
  • You manage page routing with a framework like React Router or Next.js and need to re-evaluate experiments on virtual navigation.

Sends a custom event to Optimizely for tracking conversions. Events must be created in the Optimizely app before they can be tracked.

event (custom events)
javascript
// Track a simple event
window.optimizely.push({
  type: 'event',
  eventName: 'add_to_cart',
});

// Track with tags (revenue in cents)
window.optimizely.push({
  type: 'event',
  eventName: 'purchase_completed',
  tags: {
    revenue: 4999,     // $49.99 in cents
    value: 49.99,      // Numeric value for aggregation
    product_id: 'SKU-123',
  },
});
ParameterTypeRequiredDescription
eventNamestringYesThe event key as defined in the Optimizely app under Events. Case-sensitive.
tagsobjectNoKey-value pairs attached to the event. revenue (integer, in cents) and value (float) are reserved for revenue metrics. Custom tags are stored for data export.
TagTypeDescription
revenueintegerRevenue in cents. Used by revenue metrics in Optimizely results.
valuenumberA numeric value for aggregation. Used by numeric metrics in results.

Activates a page in the Optimizely project. Use this to trigger experiments on pages in single-page applications where URL changes do not cause a full page reload.

page
javascript
// Activate a page by its API name
window.optimizely.push({
  type: 'page',
  pageName: 'product_detail_page',
});

// Activate with tags for custom analytics
window.optimizely.push({
  type: 'page',
  pageName: 'checkout_step_2',
  tags: {
    category: 'checkout',
    step: 2,
  },
});
ParameterTypeRequiredDescription
pageNamestringYesThe API name of the page as defined in the Optimizely app under Pages.
tagsobjectNoKey-value pairs sent with the page activation event.

For single-page applications, call page whenever the user navigates to a new view. This ensures experiments targeting that page are activated and impressions are tracked correctly.

// Example: React Router integration
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function OptimizelyPageTracker() {
const location = useLocation();
useEffect(() => {
const pageMap = {
'/products': 'product_listing_page',
'/cart': 'cart_page',
'/checkout': 'checkout_page',
};
const pageName = pageMap[location.pathname];
if (pageName) {
window.optimizely = window.optimizely || [];
window.optimizely.push({ type: 'page', pageName });
}
}, [location]);
return null;
}

Identifies the current visitor with a user ID and optional attributes. Attributes are used for audience targeting in experiments.

user
javascript
// Set the user ID (for cross-device tracking)
window.optimizely.push({
  type: 'user',
  userId: 'user-42',
});

// Set user attributes for audience targeting
window.optimizely.push({
  type: 'user',
  userId: 'user-42',
  attributes: {
    plan: 'enterprise',
    country: 'US',
    lifetime_value: 1250,
    is_beta_tester: true,
  },
});
ParameterTypeRequiredDescription
userIdstringNoA stable user identifier. When set, Optimizely uses this for bucketing instead of the anonymous visitor ID. Enables cross-device consistency.
attributesobjectNoA map of attribute names to values. Attribute names must match those defined in Audiences > Attributes in the Optimizely app.
  • On login — Set userId when the user authenticates so experiments are consistent across sessions and devices.
  • On page load — Set attributes from your backend (plan type, account age, etc.) before experiments activate.
  • Before activation — Attributes must be set before experiments are activated for audience conditions to evaluate correctly.

Opts the current visitor out of all Optimizely experiments. When opted out, no experiments run and no events are tracked. The opt-out state is stored in a cookie and persists across page loads.

opt-out
javascript
// Opt the user out of all experiments
window.optimizely.push({
  type: 'optOut',
  isOptOut: true,
});

// Opt the user back in
window.optimizely.push({
  type: 'optOut',
  isOptOut: false,
});

// Check opt-out status
const state = window.optimizely.get('state');
const isOptedOut = state.getRedirectInfo().isOptedOut;
ParameterTypeRequiredDescription
isOptOutbooleanYestrue to opt out, false to opt back in.
  • Cookie consent — Opt users out when they decline analytics cookies.
  • Internal traffic — Opt out employees or QA testers to avoid polluting experiment results.
  • Privacy compliance — Integrate with your consent management platform (CMP) to respect user choices.

Disables the Optimizely snippet entirely for the current page. No experiments run, no events are sent, and no cookies are written. Unlike optOut, this does not persist across page loads.

disable
javascript
// Disable Optimizely on this page
window.optimizely.push({
  type: 'disable',
});

Use disable when you need to prevent Optimizely from running on specific pages (for example, checkout confirmation pages where script execution must be minimal).

Use window.optimizely.get to read the current state of the Optimizely client.

Reading experiment state
javascript
// Get the current state object
const state = window.optimizely.get('state');

// Get active experiments
const activeExperiments = state.getActiveExperimentIds();
console.log('Active experiments:', activeExperiments);

// Get the variation for a specific experiment
const variationMap = state.getVariationMap();
for (const [experimentId, variation] of Object.entries(variationMap)) {
  console.log(`Experiment ${experimentId}: variation ${variation.id} (${variation.name})`);
}

// Get the current visitor ID
const visitorId = state.getVisitorId();
console.log('Visitor ID:', visitorId);

// Get page states
const pageStates = state.getPageStates();
for (const [pageId, pageState] of Object.entries(pageStates)) {
  console.log(`Page ${pageId}: ${pageState.apiName} — active: ${pageState.isActive}`);
}
MethodReturnsDescription
getActiveExperimentIds()string[]IDs of experiments currently active for this visitor.
getVariationMap()objectMap of experiment IDs to variation objects with id and name.
getVisitorId()stringThe anonymous visitor ID stored in the Optimizely cookie.
getPageStates()objectMap of page IDs to page state objects with apiName and isActive.
getRedirectInfo()objectInformation about redirect experiments, including whether the visitor was redirected.
getCampaignStates()objectMap of campaign IDs to their current state, including variation assignment and activation status.

The Optimizely snippet should be loaded synchronously in the <head> of your page to prevent flicker. The push-based API ensures commands are queued even if the snippet has not finished executing.

<!-- Load the Optimizely snippet synchronously -->
<script src="https://cdn.optimizely.com/js/YOUR_PROJECT_ID.js"></script>
<!-- Your code can push commands immediately -->
<script>
window.optimizely = window.optimizely || [];
window.optimizely.push({
type: 'user',
attributes: { plan: 'enterprise' },
});
</script>

If you load the snippet asynchronously (with async or defer), visitors may see the original page content before the experiment variation is applied. This is called flicker. Use the Optimizely anti-flicker snippet or synchronous loading to avoid it.