API Reference
Complete reference for the Body2FitSDK class, instance methods, events, and type definitions.
Body2FitSDK
The main class exposed by the SDK script. Instantiate it with a configuration object.
new Body2FitSDK(config: Body2FitConfig)Parameters
| Name | Type | Description |
|---|---|---|
config | Body2FitConfig | Configuration object. See Body2FitConfig for all properties. |
Quick start
The typical initialization flow looks like this:
const widget = new Body2FitSDK(config);
widget.embed(); // 1. Embed into DOM (hidden)
widget.on('ready', () => widget.open()); // 2. Open once ready
widget.on('recommendation', (data) => { // 3. Receive the recommended size
preselectSize(data.payload.recommendation.recommendedSize);
});Lifecycle order: embed() → on() → open() → close() (optional) → destroy()
For a full lifecycle breakdown with events, see Widget Lifecycle.
Static Methods
getVersion()
Returns the SDK release timestamp as a string.
Body2FitSDK.getVersion(): stringReturns: string — the Unix epoch time in milliseconds at which the loaded SDK build was released (e.g., "1777526213348"). This is not a semantic version. To get a human-readable date, pass it to new Date(Number(version)).
isProductSupported()
Checks if a product is supported by the Body2Fit service.
Body2FitSDK.isProductSupported(config: Body2FitConfig): Promise<boolean>Parameters
| Name | Type | Description |
|---|---|---|
config | Body2FitConfig | Configuration object including the garmentSKU to check. |
Returns: Promise<boolean> — resolves to true if the product is supported.
Note: This is a static method — call it before instantiating the widget to decide whether to show your size guide button at all. There is no corresponding event; support status is only available by calling this method.
Instance Methods
Constraints:
- Call
embed()beforeopen()— the widget must be in the DOM first.- Callbacks passed to
on()must be named functions to be removable withoff(). Anonymous functions cannot be removed.- Once
destroy()is called, the instance cannot be reused. Create a new instance if needed.
embed()
Embeds the widget iframe into the page. The widget is hidden initially and can be shown with open().
widget.embed(): voidopen()
Shows the widget. The widget slides in from the configured direction.
widget.open(): voidclose()
Hides the widget. The widget can be reopened with open().
widget.close(): voiddestroy()
Completely removes the widget from the page and cleans up all event listeners. The widget cannot be used after calling this method.
widget.destroy(): voidon(event, callback)
Registers an event listener for widget events. The callback is invoked whenever the event fires with the event-specific payload. Returns the widget instance for method chaining.
widget.on(event: WidgetEventName, callback: WidgetEventCallback): Body2FitSDKParameters
| Name | Type | Description |
|---|---|---|
event | WidgetEventName | Event name. See Events below. |
callback | WidgetEventCallback | Function called when the event fires. |
Unrecognized event names are ignored — the SDK logs a Unknown event type warning to the console and the callback is never registered.
widget.on('ready', () => {
widget.open();
});
widget.on('recommendation', (data) => {
console.log('Recommended size:', data.payload.recommendation.recommendedSize);
});off(event, callback)
Removes a previously registered event listener. The callback reference must be the same named function passed to on() — anonymous functions cannot be removed. Returns the widget instance for method chaining.
widget.off(event: WidgetEventName, callback: WidgetEventCallback): Body2FitSDKfunction handleRecommendation(data) {
console.log('Recommended size:', data.payload.recommendation.recommendedSize);
}
widget.on('recommendation', handleRecommendation);
// Later:
widget.off('recommendation', handleRecommendation);Events
Subscribe to events using widget.on(event, callback). The widget emits three events: ready, recommendation, and close.
Except for ready, the callback receives the raw message the widget posts to the host page — an envelope of the form { type, payload }, where type repeats the event name. Read event data from data.payload.
ready
Fires when the widget is fully loaded and ready to use. This is the appropriate time to call open() or other methods.
widget.on('ready', () => {
widget.open(); // Safe to open now
});No payload.
recommendation
Fires when the widget has computed a size recommendation for the active profile and shows the result screen. Use it to pre-select the recommended size in your product page or cart.
The event fires once per profile. If the user switches to a different saved profile and a new recommendation is produced, it fires again.
widget.on('recommendation', (data) => {
const { recommendedSize, goodFit } = data.payload.recommendation;
console.log('Recommended size:', recommendedSize); // e.g. "M"
console.log('Good fit:', goodFit);
preselectSize(recommendedSize);
});Payload
| Property | Type | Description |
|---|---|---|
type | string | Always "recommendation". |
payload.recommendation.recommendedSize | string | The recommended size label (e.g., "M", "32"). |
payload.recommendation.goodFit | boolean | Whether the recommended size is considered a good fit for the user. |
payload.profile | object | The Body2Fit profile the recommendation was computed for. See Profile. |
Note: The payload carries no product identifier — the widget is instantiated per garment, so the relevant SKU is the
garmentSKUyou passed in the config.
close
Fires when the widget is closed by the user. Use this to restore page state (e.g., scroll position, UI visibility).
widget.on('close', () => {
// e.g., restore page scroll or UI state
});Payload
| Property | Type | Description |
|---|---|---|
type | string | Always "close". |
payload | object | Empty. |
Type Definitions
Profile
The locally stored Body2Fit profile, delivered with the recommendation event. Profiles are persisted in the browser's IndexedDB on your own origin, and up to six can exist per browser.
| Property | Type | Description |
|---|---|---|
id | number | Auto-incrementing local profile ID. |
name | string | Profile display name. |
profileType | string | How the profile was created — "stats", "upload", "selfie", or "full-body". |
isActive | number | 1 for the currently selected profile, 0 otherwise. |
token | string | Bodygram token identifying the profile's measurement set. |
fromData | object | The inputs the profile was created from. |
measurements | object | The profile's body measurements. |
additionalInformation | object | Additional profile metadata. |
Body2FitConfig
interface Body2FitConfig {
// Required
clientKey: string;
countryCode: string;
languageCode: string;
brandId: string;
garmentSKU: string;
preferredMeasurementSystem: "metric" | "imperial";
// Optional
priorityFlow?: "stats" | "upload" | "selfie" | "full-body";
enabledFlows?: Array<"stats" | "upload" | "selfie" | "full-body">;
features?: string[];
brandLogoURL?: string;
garmentImageURL?: string;
garmentName?: string;
uploadAnimationURL?: string;
slideInDirection?: "left" | "right" | "top" | "bottom";
preferredGender?: "male" | "female";
privacyPolicyURL?: string;
theme?: {
[cssVariableName: string]: string | { [cssVariableName: string]: string };
dark?: { [cssVariableName: string]: string };
};
additionalParams?: Record<string, string>;
session?: {
clientSessionId?: string;
};
}Properties
| Property | Type | Required | Description |
|---|---|---|---|
clientKey | string | Yes | Your API authentication key. |
countryCode | string | Yes | ISO 3166-1 alpha-2 country code (e.g., "US", "JP"). |
languageCode | string | Yes | IETF language tag (e.g., "en", "ja"). |
brandId | string | Yes | Your brand identifier assigned by Bodygram. |
garmentSKU | string | Yes | The product SKU to get a size recommendation for. |
preferredMeasurementSystem | "metric" | "imperial" | Yes | Unit system shown to the user. |
priorityFlow | "stats" | "upload" | "selfie" | "full-body" | No | Priority input flow for the widget. Defaults to "stats". When enabledFlows is set, must be "stats" or one of enabledFlows. |
enabledFlows | Array<"stats" | "upload" | "selfie" | "full-body"> | No | Flows offered in the More methods drawer. Defaults to every flow (missing or []). "stats" is always enabled. See Configuration → Enabled flows. |
features | string[] | No | Feature flags to enable, e.g. ["shinyAvatar", "avatarLighting:studio", "weightInterval5"]. See Configuration → Features. |
brandLogoURL | string | No | URL of your brand logo shown in the widget. |
garmentImageURL | string | No | URL of the product image shown in the widget. |
garmentName | string | No | Display name of the product shown in the widget. |
uploadAnimationURL | string | No | Direct image URL shown on the photo-upload welcome screen instead of the default animation. Falls back to the default if it fails to load. See Configuration → Upload animation. |
slideInDirection | "left" | "right" | "top" | "bottom" | No | Direction the widget slides in from. Defaults to "right". |
preferredGender | "male" | "female" | No | Pre-selects the gender in the widget flow. |
privacyPolicyURL | string | No | URL of the privacy policy the widget links to. Defaults to Bodygram's Body2Fit privacy policy. See Configuration → Privacy policy. |
theme | object | No | Custom theme overrides. Keys are camelCase CSS variable names (e.g. primaryForeground → --primary-foreground). See Configuration → Theme. |
additionalParams | Record<string, string> | No | Extra parameters passed to the widget. |
session.clientSessionId | string | No | Your own session ID to correlate with Body2Fit sessions. |
Example
const config = {
clientKey: 'YOUR_CLIENT_KEY',
countryCode: 'US',
languageCode: 'en',
brandId: 'my-brand',
garmentSKU: 'SHIRT-001',
preferredMeasurementSystem: 'imperial',
garmentName: 'Classic Oxford Shirt',
garmentImageURL: 'https://example.com/images/shirt-001.jpg',
slideInDirection: 'right',
};WidgetEventName
type WidgetEventName =
| "ready"
| "recommendation"
| "close";WidgetEventCallback
type WidgetEventCallback = (data: WidgetEventData) => void;
type WidgetEventData = {
[key: string]: any;
};