JavaScript API
Use the JavaScript API to drive your own UI logic from the assigned variant. You do not need HTML visibility or dashboard CSS/JS for that — the API complements them.
Related: Events & Parameters for conversion events.
Methods
Section titled “Methods”| Method | Signature | Returns | Description |
|---|---|---|---|
getVariant | window.usertrax.getVariant(testKey) | string | null | Assigned variant ID for a test key, otherwise null |
getAssignments | window.usertrax.getAssignments() | Object | Map { [testKey]: variantKey } of all current assignments |
applyElementVisibility | window.usertrax.applyElementVisibility() | void | Re-apply HTML visibility manually (e.g. after your own DOM update) |
Assignments come from the tracker’s in-memory state and fall back to sessionStorage (usertrax_ab_<test_key>).
Examples
Section titled “Examples”// Query variant for a specific testconst variant = window.usertrax.getVariant("button_color_test");if (variant === "variant_red") { console.log("User sees red button");}
// Get all A/B test assignmentsconst assignments = window.usertrax.getAssignments();console.log("Current A/B tests:", assignments);// Different actions based on variantconst checkoutVariant = window.usertrax.getVariant("checkout_flow");
switch (checkoutVariant) { case "single_step": initSingleStepCheckout(); break; case "multi_step": initMultiStepCheckout(); break; default: initDefaultCheckout();}default covers: test inactive, not loaded yet, or unknown variant.
// Track conversion with A/B test contextfunction trackPurchase(amount) { window.usertrax.push({ event: "purchase", total: amount, currency: "USD", }); // A/B test data is automatically included}You do not set ab_test_data manually. More on events: Conversion Tracking — Events.
Queue and calling before script load
Section titled “Queue and calling before script load”Conversions can be queued before cvs.js loads — same pattern as Quick Start:
<script> window.usertrax = window.usertrax || []; // Events are fine while usertrax is still an array: window.usertrax.push({ event: "page_view" });</script><script src="https://usertrax.io/cvs.js" data-key="YOUR_API_KEY" defer></script>A/B methods are different: getVariant and getAssignments only exist after the script attaches the API to window.usertrax. Before that, window.usertrax is often just an array — method calls will fail.
For purely declarative variants you do not need this wait: the tracker applies HTML attributes and dashboard CSS/JS itself after session init.
SPA note
Section titled “SPA note”On client-side routing, the tracker re-evaluates navigations and can re-apply element visibility. If you inject markup yourself and set the attributes, call applyElementVisibility() when needed — details under Troubleshooting → SPA.