Skip to content

Experiments (SuperSDK.experiment namespace)

A/B Testing Capability · H5 reads the group assigned to this device via SuperSDK.experiment.*. Experiments are created, launched, and adjusted for traffic in the console under “Business Operations → A/B Testing”. Groups are calculated by the server based on device ID; the SDK does not implement the traffic splitting algorithm. It is responsible for fetching the result for this device, fixing the read result within the current page session, reporting exposure, and including the exposed group ID in every subsequent tracking event.

Just remember one rule: read experiments only where they are used, not by loading all experiments at startup. get(key) defaults to “read + exposure”; read experiments are recorded in experiment data. Users who didn’t see a variant are also read, which dilutes the difference between groups.

EnvironmentBehavior
Pure browser (already init(), analyticsConsent: 'granted')Fetch immediately after init() completes; the device ID is taken from the SDK’s analytics consent management (the same deviceId as used for tracking).
Pure browser · Analysis not consented (analyticsConsent: 'denied')No request is sent; get() always returns “not participated” with reason: 'no_subject'.
In-app · Container supports experiment bridge (from 2.6.0, with native SDK)Native Delegation: Fetching, freezing, and exposure, along with exp_vids, are all handled natively, sharing the same results, the same freeze table, and the same exposure deduplication logic with native code and other WebViews. H5 does not send assign requests or report exposure independently. See “In-app: Native-hosted” below.
In-app · Legacy Container (Experimental JSB not declared)Maintain the web pull path; device ID, spid, environment, platform, and App version are obtained from the host app’s getEnv(). The pull is performed only on the first call to the experiment interface.

Quick Example:

SuperSDK.init({ spid: 'ab12cd34', analyticsConsent: 'granted' });
// When using experiments on the first screen, wait for results first (up to 1.5 seconds; if timeout occurs, use the default value).
await SuperSDK.experiment.ready({ timeoutMs: 1500 });
const paywall = SuperSDK.experiment.get('paywall_price', { default: { price: '9.9' } });
renderPaywall(paywall.payload.price); // Report exposure immediately upon detection (SDK deduplication)

Wait for the first available result of this session: resolve once the first fetch on this page completes (success or failure); also resolve when timeoutMs is reached, never reject network errors. Resolve immediately if analysis consent is not granted.

ParameterTypeDescription
options.timeoutMsnumberMaximum wait time in milliseconds, default 2000
options.namespacesstring[]Add namespaces to be loaded (^[a-z][a-z0-9_]{1,31}$). By default, only default is loaded; including default, a maximum of 10 namespaces are allowed. Adding a new namespace triggers an immediate re-fetch.

Return value: Promise<void>; if parameters are invalid, reject with INVALID_ARGUMENT.

After timeout: keys that have been read retain their default values for this session; keys that have not been read take effect normally once the result arrives.

Synchronize read experiment results.

const result = SuperSDK.experiment.get('paywall_price', { default: { price: '9.9' } });
// Participate:
// { inExperiment: true, variant: 'low', vid: 10388, payload: { price: '7.9' }, reason: 'alloc' }
// Not Participated:
// { inExperiment: false, variant: '', vid: null, payload: { price: '9.9' }, reason: 'unknown' }
ParameterTypeDescription
keystringExperiment key (filled in when creating in the console)
options.defaultobjectpayload returned when not participating, default {}
options.exposebooleanWhen false, only read and freeze without reporting exposure; report exposure later using expose(key). Default is true.

Return value: ExperimentResult

FieldTypeDescription
inExperimentbooleanWhether to participate (full rollout is also true)
variantstringGroup key; empty if not participating ''
vidnumber | nullVariant ID (Experiment × Round × Group, unique within the project); null if not participating.
payloadobjectGroup parameters (JSON filled in the console for the group); if not participating, it is options.default ?? {}.
reasonstringSee the table below.
reasonMeaning
allocEnter this group based on traffic allocation.
overrideHit the mandatory list
rolloutThe experiment is fully enabled for this group; do not report exposure, and do not include in exp_vids.
unknownThis device’s result does not include this experiment (the experiment does not exist, has not been run, has not targeted the audience or traffic, and the client does not distinguish); or this is a server-side experiment (see “Server-side Experiment”).
not_loadedThis experiment belongs to a namespace that has not yet been loaded on this page (first call ready({ namespaces: [...] })); do not freeze.
no_resultNo local result yet (first access and result not yet received / SDK not initialized), or the result has not been successfully refreshed for over 7 days.
no_subjectNo device ID (analysis consent not granted)
pausedThe experiment was abruptly terminated within this page session (starting from version 2.8.0, see “Emergency Stop” below); no freeze, no exposure.

Freeze Rule: When a key is first get-ed on this page, the result (including not_loaded but excluding unavailable) is frozen until the page is unloaded; subsequent accesses to the same key always return the same result, even if a new result has arrived. Freezing applies only to the device at the time of reading: if analysis consent is withdrawn, no_subject is returned; upon re-consenting (with a new device ID), the result is re-read and frozen for the new device. New results affect only keys on this page that have not yet been read; keys that have already been read take effect only when the page is opened again. The sole exception is emergency stop.

Emergency Stop (from 2.8.0): After the console executes an “emergency stop” on an experiment, the emergency_stopped field in the pulled results lists the corresponding key (only accepting complete responses; not_modified responses and responses discarded due to outdated rules_version are ignored, consistent with native behavior). Upon receiving this, the SDK immediately unfreezes it: subsequent get calls on this page return unassigned (reason: 'paused', payload is options.default ?? {}), no longer report exposure, and its vid is removed from the set of exposed IDs. Events created thereafter will not include it in exp_vids, nor will getRequestHeaders(), appendVidsToUrl(), or fetch() carry it. One diagnostic message is sent per key (onDiagnostic receives category: 'experiment', code: 'EMERGENCY_STOPPED'). Once the experiment resumes, the key remains stopped within this page; it is only re-read upon the next page open. When delegating to native within the app, the native handles it: after get retrieves the new native result (or refresh() re-syncs), the value within the page updates to unassigned.

Exposure Rules: When participating in an experiment (alloc / override), get automatically reports an $exp_exposure event. For the same variant, there is a maximum of one report per page session and one per natural day (deduplicated via persistent storage); the business logic may call get repeatedly. No report is generated for variants not participating in the experiment or for rollout. Exposure events are reported via the analytics channel, so analyticsConsent: 'granted' is also required.

$exp_exposure parameter:

ParameterDescription
vidVariant ID
exp_keyExperiment key
exp_runround
exp_versionExperiment Configuration Version
variantGroup key
layer_keyExperiment Layer
reasonalloc / override
rules_versionThe rule version corresponding to this result
sourceweb (reported by the native when delegating to the native within the app, which is h5)

Report exposure for experiments previously read using get(key, { expose: false }). The reported group is the one frozen at the time of reading. This is used for scenarios where the experiment must be read in advance, but the user may not see the variant (e.g., preloading resources). No operation is performed if the user was not enrolled, the rollout condition was not met, or this page has not read this key before.

const banner = SuperSDK.experiment.get('home_banner', { expose: false });
preload(banner.payload.image);
// ...when the banner truly appears on the screen
SuperSDK.experiment.expose('home_banner');

For the Diagnosis and Debugging Panel: Returns { [key]: ExperimentResult & { type } }, containing all experiments (client and server) the current device participates in and the keys frozen on this page. type is 'client' or 'server' (since 2.7.0). Not frozen, not exposed; frozen keys return the frozen value. Business logic must use get(key).

Actively pull once. On network failure or rate limiting, reject with NETWORK_ERROR / TIMEOUT / RATE_LIMITED / UNAVAILABLE (local results remain available); if the server rejects (e.g., spid does not exist), reject with INVALID_ARGUMENT and include nativeCode.

Set custom audience attributes (corresponding to attr.* in the console audience conditions), debounce for 500ms, then refetch.

SuperSDK.experiment.setAttributes({ vip: '1', level: 12 }); // Report as attr.vip="1", attr.level="12"
SuperSDK.experiment.setAttributes({ vip: null }); // null / undefined Remove this property
  • The key can be written as vip or attr.vip, allowing only letters, digits, and underscores; if it contains the attr. prefix, it must not exceed 64 characters. The value must be a string, number, or boolean, and its string representation must not exceed 256 characters. A maximum of 20 key-value pairs are allowed. If these constraints are violated, INVALID_ARGUMENT is thrown during synchronization.
  • Attributes are stored only in the current page’s memory and are not persisted to disk; they must be reconfigured each time the page is opened.
  • Automatically included built-in properties of the SDK: platform: 'web' and language (original value of navigator.language) for pure browser environments; platform (android / ios) and app_version for in-app environments.

After exposure, the SDK automatically appends exp_vids to every tracking event created thereafter: the variant IDs exposed on this device, sorted in ascending order and comma-separated, e.g., "10231,10388". You can directly filter by it during analysis (e.g., exp_vids like '%10388%').

  • Take the value based on the event creation time: events generated by calling reportEvent before exposure and still in the queue to be uploaded will not include the vid from subsequent exposure.
  • Persist the set of exposed items, maintaining cross-page session validity until the experiment round concludes (the server returns a list of VIDs still in progress when fetching results, and automatically removes those that have ended).
  • The field is omitted when the collection is empty; a maximum of 500 is allowed, and new vids are not added beyond this limit (exposure events are still reported normally, and onDiagnostic receives category: 'experiment', code: 'EXP_VIDS_LIMIT').
  • exp_vids is maintained by the SDK: fields with the same name passed in addEventCommonParam are ignored in the reportEvent parameters.

2.Starting from version 7.0, the groupings of server-side experiments (console type “server-side”) are utilized by the business backend: the front end sends the set of variant IDs already exposed on this device to the backend along with the request, and the backend proceeds to the corresponding branch based on this. The value and event public parameter exp_vids represent the same set and the same string (sorted in ascending order, comma-separated), with two methods of carrying:

  • Request header X-Super-AB-Vids: 10231,10388,10412
  • query parameter super_ab_vids=10231,10388,10412 (used in scenarios where request headers cannot be set: page navigation, initial screen document requests, sendBeacon, EventSource, WebSocket handshake, form submission, <img> / <script>)
await SuperSDK.experiment.ready({ namespaces: ['feed'] });
// 1. Use the encapsulated `fetch`: Automatically merge request headers (without modifying the URL).
const res = await SuperSDK.experiment.fetch('https://api.example.com/feed', { method: 'POST', body });
// 2. Custom network library: Append after extracting the request header
axios.get('/api/feed', { headers: { ...SuperSDK.experiment.getRequestHeaders() } });
// 3. Use query parameters when headers cannot be set
location.href = SuperSDK.experiment.appendVidsToUrl('https://m.example.com/list?page=1');
MethodDescription
getRequestHeaders()Synchronously return { 'X-Super-AB-Vids': '<vids>' }; if the collection is empty, return {} (without this header).
appendVidsToUrl(url)Synchronously return the URL with super_ab_vids=<vids> appended: if a parameter with the same name already exists, it is overwritten; other parameters and the #hash are preserved; relative addresses remain relative; if the collection is empty, return the original URL. The url parameter accepts a string or URL; other types throw INVALID_ARGUMENT.
fetch(input, init?)Global fetch thin wrapper: parameters and return values are identical to fetch; merge request headers into init.headers (supports Headers, arrays, or plain objects; when input is a Request and init.headers is not provided, use its headers as the base). If the caller has already set a header with the same name, the SDK’s header takes precedence. The URL remains unchanged.

Exposure Timing: When calling the three methods above, the SDK treats all server-side experiments matched by this device within the loaded namespaces as already read: they are frozen until the end of the session, $exp_exposure is reported (with source remaining web for web and h5 for in-app), the vid is added to the exposure set, and then the string representation of the set is returned. Repeated calls within the same session do not trigger duplicate exposure. Therefore, server-side experiments must be placed in the namespace corresponding to the specific business. Only pages that have called ready({ namespaces }) to load and send the experiment logic for that business should be included, ensuring that devices that have not reached the experiment logic are not counted.

get(key) does not read server experiments: When reading a server experiment, it returns “not participated” (reason: 'unknown'), without freezing or exposure. onDiagnostic receives category: 'experiment', code: 'SERVER_EXPERIMENT_READ' (once per key). getAll() continues to list normally (type: 'server').

Requests sent by the SDK to the platform: JSON POST requests that inherently trigger CORS preflight checks in the web path (experimental assign, reportEvent for event tracking, monitoring reports, and user feedback) automatically include the X-Super-AB-Vids header, containing only the currently exposed set, and do not trigger the above “considered read” logic. When the set is empty, the header is omitted. Configuration fetching (settings GET) is a CORS simple request and does not include this header to avoid an additional preflight check for every fetch. Requests passed from the native side via JSB are determined by the native SDK.

Things you must know before integration:

  1. WebView cannot automatically add request headers to requests initiated by the page itself. Requests from H5 to its own backend must use experiment.fetch, or manually attach headers via getRequestHeaders() / appendVidsToUrl(). The same applies to in-app scenarios. The SDK will not automatically rewrite any business URLs.
  2. Cross-origin requests trigger a preflight. When the page and backend are not on the same origin, custom request headers cause the browser to first send an OPTIONS request; the backend’s Access-Control-Allow-Headers must include X-Super-AB-Vids, otherwise the request is blocked by the browser. If modifying CORS is inconvenient, use a query parameter instead.
  3. Backend read order: Request headers take precedence, followed by query parameters; if both are present and inconsistent, the request headers prevail.
  4. Request headers and query parameters can be tampered with by users. For judgments involving price, quota, or entitlement, the backend must not rely solely on them; instead, use device_id to call assign (side: "server") for verification. Experiments that only affect display or sorting can directly read the request headers.
  5. The value is null before the result is received (on first launch, before assign returns; before ready() within the app), and the backend processes it using default logic. To include the experiment in the first request, call await SuperSDK.experiment.ready() first.
  6. Closing sequence: The backend first changes the winning logic to the default and deploys it, then ends the experiment in the console (server-side experiments do not support “full rollout”; after ending, the vid is removed from the collection).
  7. URL Length: When the number of vids approaches 500, the query parameters become very long. Some legacy proxies have a 2 KB URL length limit, so prefer using request headers when possible. Additionally, do not append parameters to cacheable static resource URLs, as this will invalidate CDN caching.

When a container declares all five JSB methods experimentReady, getAllExperiments, getExperiment, exposeExperiment, and setExperimentAttributes simultaneously (via SuperSDK.bridge.supports(...) or through the new protocol manifest or legacy bridge with matching function names), SuperSDK.experiment automatically delegates to the native layer, with the interface and return values remaining unchanged. Once a page enters delegation mode, it will not switch back.

  • ready(options?): Invokes the native experimentReady (passing through timeoutMs / namespaces), then uses getAllExperiments to mirror the current native results into page memory. Never rejects; if the native call fails, onDiagnostic receives category: 'experiment_native'.
  • get(key, options?): Remains synchronous—reads the mirror and freezes the value in the current page, while asynchronously invoking getExperiment to freeze the value in the native environment and (by default) trigger an exposure. If the native environment has already frozen a different result (e.g., the native code read it first), the native value takes precedence: the mirror and the current page’s frozen value are corrected accordingly, and onDiagnostic receives code: 'NATIVE_RESULT_MISMATCH'. Subsequent get calls return the native value.
  • Read before ready(): Returns uninvolved (reason: 'no_result') and frozen on this page, without notifying the native SDK (to avoid native exposure of a variant that is not displayed on the page) — consistent with “read before result arrival” on the web. Therefore, the app’s first screen must also await ready() during experiment execution.
  • expose(key) → exposeExperiment; setAttributes(map) → setExperimentAttributes (validation rules remain the same; debouncing and re-fetching are handled by the native layer; attributes are shared within the native process and are no longer scoped to the current page).
  • getAll() returns the mirror plus the frozen value of the current page; refresh() re-reads the current native result (native self-schedules pull: on startup, when returning to the foreground after 10 minutes, when changing attributes, or when switching environments), and rejects on failure.
  • Exposure and exp_vids: Exposure is reported natively, with source set to h5; all in-app tracking points are passed to the native layer via JSB reportEvent. exp_vids is written by the native layer when the event is created and is not included in the JSSDK (named parameters passed by the caller are discarded as usual).
  • Native sessions are bounded by the app process (a session is considered new if the app is sent to the background for more than 30 minutes), not by page unloads. When an in-app page is reopened, frozen experiments in the client still return the same results.
  • Server-side Experiments (from 2.7.0): Each item returned by getAllExperiments includes type and exposed. getRequestHeaders(), appendVidsToUrl(), and fetch() remain synchronous—calculating values via the mirror (exposed vid + server-side experiment vid that matched), while asynchronously invoking the JSB getExperimentRequestVids to let the native layer fix and expose them (source: 'h5'). The native layer’s returned collection takes precedence; if inconsistent, onDiagnostic receives code: 'NATIVE_RESULT_MISMATCH'. Before ready(), an empty result is returned and no native call is made. If the container does not declare getExperimentRequestVids (legacy native SDK), only mirror-based calculation is performed, and onDiagnostic receives a single code: 'REQUEST_VIDS_UNSUPPORTED'.

The following describes the behavior for web paths (pure browsers and legacy containers); when delegated to native, it is handled by the native SDK.

  • Pull Timing: Pull immediately after init() completes and a device ID is available; pull again when a page transitions from hidden to visible and more than 10 minutes have passed since the last successful pull; also pull after setAttributes, when adding new namespaces via ready({ namespaces }), and during refresh(). The request is POST {baseUrl}/v2/experiments/assign, using the same set of baseUrls as tracking (with fallback rotation on failure) and supporting suenc response decoding.
  • Local Cache: Results are stored in localStorage using the key prefix supersdk_exp_v1: with the composite key spid + project environment + device ID. In cases of network failure or rate limiting, the local result is used. If a local result has not been successfully refreshed for over 7 days, it is considered invalid (no_result).
  • Consent: When analysis consent is set to denied, no requests are sent and get returns no_subject; calling setAnalyticsConsent('denied') clears local experiment results and the exposure set, and previously frozen results are no longer returned; switching to granted triggers an immediate re-fetch.
  • Switch project environment: After calling setAPIEnvironment(), use the new environment’s independent cache and re-fetch.