Bodygram

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

NameTypeDescription
configBody2FitConfigConfiguration 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(): string

Returns: 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

NameTypeDescription
configBody2FitConfigConfiguration 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() before open() — the widget must be in the DOM first.
  • Callbacks passed to on() must be named functions to be removable with off(). 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(): void

open()

Shows the widget. The widget slides in from the configured direction.

widget.open(): void

close()

Hides the widget. The widget can be reopened with open().

widget.close(): void

destroy()

Completely removes the widget from the page and cleans up all event listeners. The widget cannot be used after calling this method.

widget.destroy(): void

on(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): Body2FitSDK

Parameters

NameTypeDescription
eventWidgetEventNameEvent name. See Events below.
callbackWidgetEventCallbackFunction 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): Body2FitSDK
function 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

PropertyTypeDescription
typestringAlways "recommendation".
payload.recommendation.recommendedSizestringThe recommended size label (e.g., "M", "32").
payload.recommendation.goodFitbooleanWhether the recommended size is considered a good fit for the user.
payload.profileobjectThe 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 garmentSKU you 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

PropertyTypeDescription
typestringAlways "close".
payloadobjectEmpty.

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.

PropertyTypeDescription
idnumberAuto-incrementing local profile ID.
namestringProfile display name.
profileTypestringHow the profile was created — "stats", "upload", "selfie", or "full-body".
isActivenumber1 for the currently selected profile, 0 otherwise.
tokenstringBodygram token identifying the profile's measurement set.
fromDataobjectThe inputs the profile was created from.
measurementsobjectThe profile's body measurements.
additionalInformationobjectAdditional 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

PropertyTypeRequiredDescription
clientKeystringYesYour API authentication key.
countryCodestringYesISO 3166-1 alpha-2 country code (e.g., "US", "JP").
languageCodestringYesIETF language tag (e.g., "en", "ja").
brandIdstringYesYour brand identifier assigned by Bodygram.
garmentSKUstringYesThe product SKU to get a size recommendation for.
preferredMeasurementSystem"metric" | "imperial"YesUnit system shown to the user.
priorityFlow"stats" | "upload" | "selfie" | "full-body"NoPriority input flow for the widget. Defaults to "stats". When enabledFlows is set, must be "stats" or one of enabledFlows.
enabledFlowsArray<"stats" | "upload" | "selfie" | "full-body">NoFlows offered in the More methods drawer. Defaults to every flow (missing or []). "stats" is always enabled. See Configuration → Enabled flows.
featuresstring[]NoFeature flags to enable, e.g. ["shinyAvatar", "avatarLighting:studio", "weightInterval5"]. See Configuration → Features.
brandLogoURLstringNoURL of your brand logo shown in the widget.
garmentImageURLstringNoURL of the product image shown in the widget.
garmentNamestringNoDisplay name of the product shown in the widget.
uploadAnimationURLstringNoDirect 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"NoDirection the widget slides in from. Defaults to "right".
preferredGender"male" | "female"NoPre-selects the gender in the widget flow.
privacyPolicyURLstringNoURL of the privacy policy the widget links to. Defaults to Bodygram's Body2Fit privacy policy. See Configuration → Privacy policy.
themeobjectNoCustom theme overrides. Keys are camelCase CSS variable names (e.g. primaryForeground → --primary-foreground). See Configuration → Theme.
additionalParamsRecord<string, string>NoExtra parameters passed to the widget.
session.clientSessionIdstringNoYour 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;
};

On this page