Skip to content

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.

MethodSignatureReturnsDescription
getVariantwindow.usertrax.getVariant(testKey)string | nullAssigned variant ID for a test key, otherwise null
getAssignmentswindow.usertrax.getAssignments()ObjectMap { [testKey]: variantKey } of all current assignments
applyElementVisibilitywindow.usertrax.applyElementVisibility()voidRe-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>).


// Query variant for a specific test
const variant = window.usertrax.getVariant("button_color_test");
if (variant === "variant_red") {
console.log("User sees red button");
}
// Get all A/B test assignments
const assignments = window.usertrax.getAssignments();
console.log("Current A/B tests:", assignments);

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.


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.