/Docs

Snippet SDK API

The A vs B snippet exposes two programming interfaces: the global window.avsb object (available anywhere on the page) and the options toolkit (available inside initVariation, initTrigger, and initProject). Use the global API for page-level concerns; use options for anything scoped to a specific variation or project setup run.

Global API — window.avsb

When the A vs B snippet loads on your page, it attaches a global object called window.avsb. This object is your programmatic interface to the experiment engine — you can track conversions, read which variation a visitor is seeing, force a specific variation for testing, wait for dynamic elements to appear, and hook into the event stream for analytics integrations.

Full interface

Here is the complete TypeScript interface for window.avsb. All methods are available as soon as the snippet has finished initializing, which happens before the page's DOMContentLoaded event fires.

window.avsb interface
typescript
1// A wait target: CSS selector, window.x.y global path, or predicate function
2type WaitTarget<T = unknown> = string | (() => T)
3
4interface WaitOptions {
5 timeout?: number // ms before the wait times out — default 10000
6 all?: boolean // when true, selector resolves with querySelectorAll array
7}
8
9// Promise-like whose .catch() is OPTIONAL — failures log gracefully
10interface GuardedThenable<T> {
11 then(onFulfilled?, onRejected?): GuardedThenable<...>
12 catch(onRejected?): GuardedThenable<...>
13 finally(onFinally?): GuardedThenable<...>
14 stop(): void // cancel the wait engine
15}
16
17interface IntegrationEvent {
18 experiment_id: string
19 experiment_name: string
20 variation_id: string
21 variation_name: string
22 event_name: string
23 revenue?: number
24}
25
26interface AvsbTrack {
27 event: (shortId: number, properties?: { revenue?: number }) => void
28 segment: (segmentKey: string, segmentValue: string) => void
29}
30
31interface Avsb {
32 init: () => void | Promise<void>
33 disable: () => void
34 track: AvsbTrack
35 getVisitorId: () => string
36 getVariation: (experimentId: string) => string | null
37 getActiveExperiments: () => Array<{ experimentId: string; variationId: string }>
38 forceVariation: (experimentId: string, variationId: string) => boolean
39 // Single target
40 waitUntil<T>(target: WaitTarget<T>, opts?: WaitOptions): GuardedThenable<T>
41 // Multiple targets — resolves with array of results
42 waitUntil<T extends unknown[]>(targets: WaitTarget[], opts?: WaitOptions): GuardedThenable<T>
43 utils: AvsbUtils // see avsb.utils reference for full shape
44 onEvent?: (event: IntegrationEvent) => void
45}
46
47declare global {
48 interface Window {
49 avsb: Avsb
50 }
51}
Snippet must be loaded first
window.avsbis only defined after the snippet script has loaded and executed. If you call any method before the snippet is ready, you will get a "cannot read properties of undefined" error. The snippet initializes synchronously once its script tag runs, so placing it early in <head> is the safest approach. For code that may run before the snippet, guard with if (window.avsb) { ... }.

Method reference

avsb.init

avsb.init() => void | Promise<void>

Starts the snippet when Consent Mode is enabled. Triggers cookie creation, experiment evaluation, variation injection, and event tracking. Has no effect when Consent Mode is off (the snippet auto-initializes), when already initialized, or after disable() has been called. Any track calls queued before init() are replayed after initialization completes.

avsb.disable

avsb.disable() => void

Stops all tracking, clears the visitor cookie, removes injected variations, and tears down experiment triggers. After calling disable(), init() becomes a no-op — the visitor must reload the page to re-consent. Use this when a visitor revokes cookie consent.

avsb.track.event

avsb.track.event(shortId: number, properties?: { revenue?: number }) => void

Records a conversion for a custom event metric. The shortId is the numeric ID shown next to the metric name on the Metrics page. An optional revenue property attaches a monetary value to the conversion, which unlocks the Revenue Impact calculation in experiment results. Each visitor can only convert once per metric — subsequent calls for the same metric are silently ignored.

avsb.track.segment

avsb.track.segment(segmentKey: string, segmentValue: string) => void

Assigns a custom attribute to the current visitor. Segments defined here appear as filter options on the experiment results page, letting you slice results by any visitor property — subscription plan, account tier, locale, and so on. The segment must be defined in your organization settings before the call takes effect.

avsb.getVisitorId

avsb.getVisitorId() => string

Returns the persistent visitor ID assigned to the current browser. This ID is stored in the _avsb_visitor cookie and stays constant across page loads and sessions on the same device. Useful when you need to correlate A vs B data with records in your own database or analytics system.

avsb.getVariation

avsb.getVariation(experimentId: string) => string | null

Returns the variation ID that the current visitor has been assigned to for the given experiment. Returns null if the visitor is not in the experiment (because they do not match the targeting rules, or because they are in the holdout group). The experimentId is the ID shown in the experiment overview panel — it starts with exp_.

avsb.getActiveExperiments

avsb.getActiveExperiments() => Array<{ experimentId: string; variationId: string }>

Returns the list of all experiments the current visitor is currently active in, as an array of { experimentId, variationId } pairs. Useful for debugging multi-experiment pages or for passing experiment context to an analytics system.

avsb.forceVariation

avsb.forceVariation(experimentId: string, variationId: string) => boolean

Forces the current visitor into a specific variation of an experiment, overriding normal bucketing. Returns true if the variation was applied successfully, false if the experimentId or variationId could not be found. Use this for QA testing — you can call it from the browser DevTools console to immediately switch to any variation. The forced assignment is stored in the visitor's cookie and persists across page loads.

avsb.waitUntil

avsb.waitUntil(target, opts?: { timeout?: number; all?: boolean }) => GuardedThenable

Promise-based wait for a CSS selector, a window.x.y global path, a predicate function, or an array of these. Chains with .then() — no .catch() required, because a failed or timed-out wait is logged gracefully instead of raising an unhandled-rejection error. Call .stop() on the returned GuardedThenable to cancel early. Default timeout is 10000 ms. Note: this is the global form — it is NOT automatically cleaned up when a variation is removed. Inside trigger and variation code, prefer options.waitUntil, which is auto-cleaned on teardown. See the Wait Until reference page for the full parameter table and examples.

avsb.utils

avsb.utils: AvsbUtils

A toolkit of helpers for variation and trigger code: wait utilities (waitUntil, poll, waitForElement, onMutation), timing helpers (once, throttle, debounce, raf, idle, domReady, retry), DOM manipulation ($, $$, createElement, insertAfter, insertBefore, wrap, remove, setText, setHtml), event utilities (on with delegation, onUrlChange), data access (cookie, query, storage.local, storage.session, state), and a scoped logger (log). Also accessible as options.utils inside trigger and variation code, where every observer and listener is auto-cleaned on variation removal. See the Utilities reference page for descriptions and examples of every helper.

avsb.onEvent

avsb.onEvent = (event: IntegrationEvent) => void

An optional callback you can set to receive experiment events in real time. Assign a function to window.avsb.onEvent and it will be called each time a visitor is bucketed into a variation, sees a variation, or triggers a conversion. Use this to pipe experiment data into your own analytics platform without any server-side integration.

The options toolkit — inside user code

Every user-written code surface (initVariation, initTrigger, initProject) receives an options object as its first argument. This toolkit is distinct from the global window.avsb API: it is scoped to the current variation or project run, and the self-cleaning helpers within it are automatically torn down when that run ends.

options toolkit interface (available in user code)
typescript
1// Context — available in initVariation
2// Note: initVariation runs only after activation — apply changes directly in
3// the function body. onActivation is NOT present; use onRemove for teardown.
4interface VariationOptions {
5 experimentId: string
6 experimentName: string
7 variationId: string
8 variationName: string
9 variationType: 'control' | 'variant'
10
11 // Teardown hook — fires on SPA navigation, experiment end, or avsb.disable()
12 onRemove: (callback: () => void) => void
13
14 // Self-cleaning helpers — all auto-cancelled on variation removal
15 waitUntil(target: WaitTarget | WaitTarget[], opts?: WaitOptions): GuardedThenable<unknown>
16 utils: AvsbUtils // full toolkit — see Utilities reference
17 setTimeout: (fn: () => void, ms?: number) => { cancel: () => void }
18 setInterval: (fn: () => void, ms?: number) => { cancel: () => void }
19 addEventListener: (target: EventTarget, type: string, handler: EventListenerOrEventListenerObject, opts?: AddEventListenerOptions) => void
20
21 // Tracking
22 track: { event: (shortId: number, properties?: { revenue?: number }) => void; segment: (key: string, value: string) => void }
23 getVisitorId: () => string
24 getVariation: (experimentId: string) => string | null
25 getActiveExperiments: () => Array<{ experimentId: string; variationId: string }>
26 forceVariation: (experimentId: string, variationId: string) => boolean
27}
28
29// Context — available in initProject (subset, no variation fields)
30// Note: initProject runs on every page load and SPA navigation — there is no
31// activation gate. Apply setup directly in the function body. onActivation is
32// NOT present; use onRemove for pre-navigation teardown.
33interface ProjectOptions {
34 projectId: string
35
36 // Teardown hook — fires before each SPA navigation re-run
37 onRemove: (callback: () => void) => void
38
39 waitUntil(target: WaitTarget | WaitTarget[], opts?: WaitOptions): GuardedThenable<unknown>
40 utils: AvsbUtils // full toolkit — see Utilities reference
41 setTimeout: (fn: () => void, ms?: number) => { cancel: () => void }
42 setInterval: (fn: () => void, ms?: number) => { cancel: () => void }
43 addEventListener: (target: EventTarget, type: string, handler: EventListenerOrEventListenerObject, opts?: AddEventListenerOptions) => void
44
45 track: { event: (shortId: number, properties?: { revenue?: number }) => void; segment: (key: string, value: string) => void }
46 getVisitorId: () => string
47 getVariation: (experimentId: string) => string | null
48 getActiveExperiments: () => Array<{ experimentId: string; variationId: string }>
49 forceVariation: (experimentId: string, variationId: string) => boolean
50}
Prefer options helpers over global avsb inside user code
Inside initVariation, initTrigger, and initProject, always use options.waitUntil, options.setTimeout, options.setInterval, and options.addEventListener rather than their global equivalents. The options versions are automatically cancelled when the variation or project run is torn down (for example, on SPA navigation), preventing memory leaks and stale callbacks.

Deep dives

Each method has a dedicated page with parameter tables, detailed explanations, and code examples covering common scenarios.