Widget SDK
The widget SDK is the JavaScript API on window.FluentChat. You use it to mount the widget, control it from your own buttons, listen to its events, pass page context, and connect website callbacks.
Get the install code from Bot > Channels > Chat bubble: select Add to website, then Website widget. Center stage has the same panel.
Before you start
- An enabled website channel. In Bot > Channels, turn on the channel’s availability switch, such as Chat bubble availability. The SDK can’t show a channel that’s off.
- The JavaScript install code. The iframe embed doesn’t expose the SDK: “For host-page events and signed visitor identity, use the JavaScript widget.”
- Your bot ID. The install code includes it.
Install the widget
-
Copy the install code. In Website widget, select Copy install code.
-
Paste it before
</body>. Add it to every page that should show chat. Don’t addasyncordeferto the first script tag; the inline script needs it loaded first. -
Keep the handle. The install code saves the widget handle as
window.fluentChatWidget. Use that handle for every method on this page.
The install code looks like this. Copy the real code from Add to website > Website widget: it contains your bot ID and the correct script address, shown here as YOUR_WIDGET_HOST. Center stage’s code also passes layout: "center-stage".
<script src="https://YOUR_WIDGET_HOST/fluentchat-loader.js"></script><script> if (typeof window.FluentChat?.mount === "function") { window.FluentChat.mount({ botId: "YOUR_BOT_ID" }).then( widget => { window.fluentChatWidget = widget; }, () => console.warn("Chat is temporarily unavailable.") ); } else { console.warn("Chat is temporarily unavailable."); }</script>The small fluentchat-loader.js script defines window.FluentChat with mount() and version. It loads the full widget the first time you call mount().
Use a JavaScript module
In a module-based app, import the widget entry directly instead of using the loader. It lives next to the loader on the same host: replace fluentchat-loader.js in your install code with chat-widget.js.
import { FluentChat } from "https://YOUR_WIDGET_HOST/chat-widget.js";
const widget = await FluentChat.mount({ botId: "YOUR_BOT_ID" });Mount the widget
FluentChat.mount(options) returns a promise. It resolves with a widget handle once the widget is ready, or rejects with a WidgetSdkError. Each call creates its own independent widget with its own handle.
const widget = await window.FluentChat.mount({ botId: "YOUR_BOT_ID", layout: "center-stage", options: { messagePlaceholder: "Ask about your order" },});Mount options
| Option | Type | Required | Description |
|---|---|---|---|
botId | string | Yes | Your bot ID. |
layout | string | No | How the widget appears. Defaults to bubble. See Layouts. |
target | string or element | For some layouts | A CSS selector or element to render into. Required for inline, iframe, and help-page; not allowed for the others. |
identityToken | string | No | A signed JWT for a signed-in visitor. See Identity verification. |
identityChecking | boolean | No | true hides the widget until you call setIdentityChecking(false). Use it while your page checks whether the visitor is signed in. |
options | object | No | Display overrides for this widget only. See Display options. |
userMetadata | object | No | Unsigned JSON, up to 1,000 characters, passed to your form schema handlers as user.user_metadata. |
signal | AbortSignal | No | Aborting it cancels a pending mount, which rejects with widget_destroyed. |
connection, verifiedConnection, previewToken, appearance | string | No | Reserved for the FluentChat WordPress connector, dashboard previews, and the help-page layout. Leave them out in your own code. |
Any other option, including the old visitor object, makes mount() reject with invalid_configuration.
Layouts
| Layout | What it shows | Channel it uses |
|---|---|---|
bubble | A floating launcher that opens the chat. | Chat bubble |
center-stage | A composer at the bottom center that expands into a conversation card. | Center stage |
inline | The chat inside your target element, open on load. | Help page |
iframe | The chat inside your target element, open on load, with Chat bubble settings. | Chat bubble |
help-page | The full Help page, with navigation and suggestions, inside your target element. | Help page |
The target must be an element on the page other than <body> or <html>. A selector can be up to 256 characters.
<div id="support-page"></div><script> window.FluentChat.mount({ botId: "YOUR_BOT_ID", layout: "help-page", target: "#support-page", options: { helpPage: { welcome: "How can we help with your account?" } }, }).then(widget => { window.supportPage = widget; });</script>Widget handle
mount() resolves with a handle. Methods throw widget_not_ready while the widget is starting or switching identity, and widget_destroyed after destroy().
Visibility
| Method | What it does |
|---|---|
open() | Opens the widget. |
close() | Closes the widget. |
toggle() | Opens or closes the widget. |
maximize() | Opens the widget at full size. Works in the bubble layout. |
minimize() | Returns a maximized widget to normal size. |
document.querySelector("#help-button").addEventListener("click", () => { window.fluentChatWidget.open();});Messages and conversations
| Method | What it does |
|---|---|
sendMessage({ message, hideMessage }) | Sends a message as the visitor. Resolves when FluentChat accepts it, with { commandId, messageId, conversationId, turnId }. It doesn’t wait for the answer. |
open({ message, hideMessage }) | Sends a message and opens the widget. With hideMessage: true, the widget opens once the answer starts. |
resetChat() | Starts a new conversation. It doesn’t sign the visitor out. |
selectConversation(id) | Opens one of the visitor’s conversations. Use an ID from the conversation.changed event’s conversations list. |
openComposer() | In the help-page layout, shows the composer while a human agent handles the conversation. |
message must be 1 to 32,000 characters and not blank. With hideMessage: true, the visitor doesn’t see the message in the chat, but the bot still receives it. Send one message at a time; a second call before the first finishes rejects with message_in_progress.
const receipt = await window.fluentChatWidget.open({ message: "Where is my order?",});console.log(receipt.conversationId);Context and identity
| Method | What it does |
|---|---|
setContext(context) | Replaces the public page context sent with the visitor’s next messages to the AI. See Public context. |
identify(token) | Switches to a signed-in visitor with a JWT from your server. Also accepts { token, user_metadata }. |
logout() | Switches back to an anonymous visitor. |
setIdentityChecking(checking) | true hides the widget and blocks controls while your page checks sign-in state. false shows it again. |
identify() and logout() keep the same handle, your event listeners, display options, and registered callbacks. They replace the conversation view, drafts, and context. See Identity verification.
Display
| Method | What it does |
|---|---|
setTheme(theme, primaryColor) | Sets light or dark. primaryColor is a six-digit hex color and applies in the help-page layout. |
getOptions() | Returns this widget’s current display overrides. |
setOptions(options) | Merges display overrides. See Display options. |
resetOptions(selection) | Removes overrides. With no argument, restores all saved defaults. { appearance: true } resets one group. |
Website callbacks
| Method | What it does |
|---|---|
registerTools(handlers) | Registers functions for Run client-side code actions, keyed by Callback name. |
registerFormSchema(schemas) | Supplies fields for Custom form actions whose Form source is Website-registered form (advanced). |
registerForms(forms) | Relabels the fields of a Custom form action by its Host form name. |
getActionReadiness() | Returns { registered, polling, registeredForms, mismatchedForms } so you can check registrations. It doesn’t run callbacks. |
See Website callbacks for examples.
Events and lifecycle
| Member | What it does |
|---|---|
on(event, listener) | Subscribes to an event. Returns a function that unsubscribes. |
off(event, listener) | Unsubscribes a listener. |
once(event, listener) | Subscribes for one event only. |
destroy() | Removes the widget, its connection, and its timers. Conversations aren’t deleted. |
id | This widget’s instance ID. |
ready | A promise that resolves when the widget first became ready. |
Events
const stop = window.fluentChatWidget.on("message.received", (message) => { console.log(message.role, message.text);});
// Later:stop();| Event | Payload | When |
|---|---|---|
initialized | { version, instanceId } | The widget is ready, including after identify() or logout(). |
visibility.changed | { open } | The widget opened or closed. |
connection.changed | { status } | The connection changed to connecting, connected, or disconnected. |
conversation.changed | { conversationId, busy, conversations, ... } | The active conversation or the visitor’s conversation list changed. |
options.changed | { options, greetingTiming } | Display options changed. |
message.sent | { commandId, messageId, conversationId, turnId, role, text, hidden } | A visitor or host message was accepted. role is visitor or host. |
message.received | { messageId, conversationId, role, text } | A new answer arrived in the active conversation. role is assistant or agent. |
turn.started | { conversationId, turnId } | The bot started answering. |
turn.completed | { conversationId, turnId, text } | The bot finished answering. |
turn.failed | { conversationId, turnId } | The answer failed. |
identity.expired | {} | The visitor’s token expired. The widget switches to an anonymous visitor. |
composer.retry | { text } | In the help-page layout, the visitor chose to retry a message. |
error | { code } | Something failed. See Errors. |
A new listener for initialized, visibility.changed, connection.changed, conversation.changed, or options.changed immediately receives the latest value. Message and turn events aren’t replayed. Listeners get a copy of the payload, and an error thrown in a listener doesn’t affect the widget.
Public context
setContext() tells the AI non-secret facts about the visitor’s current page, such as the section or plan. The widget sends the context with each later visitor message to the AI.
window.fluentChatWidget.setContext({ section: "Billing", plan: "starter", items: 2 });
// Replaces the whole context; it doesn't merge.window.fluentChatWidget.setContext({ section: "Help" });
// Clears it.window.fluentChatWidget.setContext({});| Rule | Limit |
|---|---|
| Keys | Up to 16. Each starts with a letter and has up to 64 letters, digits, _, or -. |
| Values | Strings up to 512 characters, finite numbers, true, false, or null. |
| Total size | 8 KB as JSON. |
| Reserved keys | Identity and authority keys, such as email, name, user_id, token, permissions, and system_prompt, are rejected. |
Invalid input throws invalid_context and keeps the previous context. The AI treats context as untrusted page data. It doesn’t grant actions or change the visitor’s profile. identify(), logout(), and destroy() clear it.
Website callbacks
Run client-side code
A Run client-side code action calls a function on your page. Register the function under the action’s Callback name; the name must match exactly. See Custom action.
window.fluentChatWidget.registerTools({ check_order_status: async ({ order_id }, { signal }) => { const response = await fetch(`/api/orders/${encodeURIComponent(order_id)}`, { signal }); if (!response.ok) throw new Error("Order lookup failed"); const order = await response.json(); return { status: order.status }; },});
console.table(window.fluentChatWidget.getActionReadiness());- The callback gets two arguments. The inputs the AI passes, and a context with
botId,conversationId,turnId,invocationId, andsignal. - Return JSON only. Results can be up to 20,000 characters, 1,024 values, and 12 levels deep.
- Callbacks have 30 seconds. “Missing callbacks and failed or late results are reported as unsuccessful.”
- Each call replaces the whole set. Register up to 32 callbacks at once, named with lowercase letters, digits, and
_.registerTools({})removes them. - Registering grants nothing. The action must also be enabled and allowed on the channel. Check permissions on your server for anything that changes customer data.
Website-registered forms
When a Custom form action’s Form source is Website-registered form (advanced), your page supplies the fields. Register the handler under the action name the editor shows. See Collect data and custom forms.
window.fluentChatWidget.registerFormSchema({ support_request_form: async (args, user) => ({ fields: [ { name: "order_id", label: "Order number", type: "text", validation: { required: { value: true } } }, { name: "topic", label: "Topic", type: "select", options: [ { value: "billing", label: "Billing" }, { value: "shipping", label: "Shipping" }, ], }, { name: "details", label: "Details", type: "textarea", validation: { maxLength: { value: 500 } } }, ], submitButtonText: "Send request", successMessage: "Thanks, we've got your request.", }),});- The handler gets two arguments. The inputs the AI passes when it opens the form, and a
userobject withuser_metadata(fromuserMetadataoridentify()) and, for a verified visitor,user_id. - Return 1 to 20 fields. Each needs a
name(letters, digits, and_, up to 40), alabel(up to 80 characters), and atype. - Field types:
text,textarea,email,phone,number,boolean,date,image,select,multiselect,groupselect,groupmultiselect. - Choices: select types take up to 30
{ value, label }options, each up to 100 characters. - Validation:
required,minLength,maxLength,min,max, andpattern, each as{ value }. - Return within 10 seconds. Otherwise the visitor sees “The form took too long to load.”
- Register up to 16 forms. An unregistered name shows “This form is not registered on this website.”
Relabel a built-in form
registerForms() changes the labels and help text of a Custom form whose Host form name matches the key. Pass the same fields in the same order, with the same keys, types, and validation. Help text can be up to 300 characters. If the fields don’t match, the widget keeps the dashboard labels and lists the form in mismatchedForms.
Display options
Pass display overrides in mount({ options }) or setOptions(). They apply to that widget only and never change saved settings, instructions, actions, or identity.
const result = await window.fluentChatWidget.setOptions({ messagePlaceholder: "Ask about your order", appearance: { primaryColor: "#2563eb", buttonAlignment: "left" },});console.log(result.issues); // Fields that were rejected, with a reason code.setOptions() resolves with { accepted, cleared, issues, greetingTiming }. Valid fields apply even when others are rejected. greetingTiming is immediate, next-conversation, or unchanged; new greeting messages wait for the next conversation when one is already open.
| Option | Type | Limit |
|---|---|---|
displayName | string | 100 characters |
bubbleText | string | 40 characters |
footer | string | 1,000 characters |
messagePlaceholder | string | 100 characters |
dismissibleNotice | string | 500 characters |
initialMessages | array of strings | 1,000 characters in total |
suggestedMessages | array of strings | 10 items, 200 characters each |
floatingInitialMessages | { enabled, delayMs, oncePerSession } | delayMs from 0 to 60000, default 2000; oncePerSession defaults to true |
appearance | object | primaryColor, secondaryColor, onPrimaryColor, onSecondaryColor, theme (light, dark, auto), headerLogo, botIcon, buttonIcon, buttonAlignment (left, right), headerStyle (solid, gradient, minimal), pictureBorder |
centerStage | object | theme, heading, placeholder, displayName, pictureUrl, pictureBorder, fontFamily, fontSize, width (400–720), height (480–1000), bottomOffset (8–96), headerStyle, headerColor, headerGradientEnd, accentColor, accentEnabled, tinted, tintedGrayscale, noticeText, footerText |
helpPage | object | title, welcome, placeholder, theme, themeSwitch, lightPrimaryColor, darkPrimaryColor, logoUrl, darkLogoUrl, heroUrl, darkHeroUrl, fieldGlow, primaryLabel, primaryUrl, secondaryLabel, secondaryUrl, primaryEnabled, secondaryEnabled, suggestionsEnabled, linksEnabled, suggestedMessages, links |
Colors are six-digit hex values, such as #2563eb. Image and link fields take an http or https URL, or an empty string to remove the image. An empty string or array clears text content. Center stage fonts are Inter, System, Arial, Helvetica, Georgia, or Geist, in sizes 12, 14, 16, 18, or 20. Help page suggestedMessages and links take up to four items each.
Errors
Methods throw, or promises reject with, a WidgetSdkError that has a code. The error event reports the same codes.
try { await window.fluentChatWidget.sendMessage({ message: "Hello" });} catch (error) { console.warn(error.code);}| Code | Meaning |
|---|---|
bundle_unavailable | The widget script couldn’t load. |
invalid_configuration | A mount option or method argument isn’t valid. |
initialization_failed | The widget couldn’t start. |
connection_unavailable | The widget couldn’t connect to FluentChat. |
identity_rejected | FluentChat rejected the identity token. |
identity_in_progress | An identify() or logout() call is still running. |
widget_not_ready | The widget is starting or switching identity. |
widget_destroyed | The widget was destroyed, or the mount was aborted. |
invalid_listener | The event name is unknown, or the listener isn’t a function. |
invalid_message | The message is empty, too long, or has unknown fields. |
invalid_context | setContext() input broke a context rule. |
message_rejected | FluentChat didn’t accept the message. |
message_in_progress | Another message is still being sent or answered. |
acceptance_uncertain | The widget couldn’t confirm the message was accepted. Don’t resend it automatically. |
reply_failed | The answer to a hidden message failed. |
Single-page apps
- Mount once. Mount at app start and keep the handle across route changes. Each
mount()call creates another widget. - Destroy on teardown. Call
destroy()when a view that owns the widget unmounts. To cancel a mount that hasn’t finished, abort itssignal. - Wait for sign-in state. Mount with
identityChecking: truewhile you check the session, then callidentify()orsetIdentityChecking(false).
const controller = new AbortController();const widget = await window.FluentChat.mount({ botId: "YOUR_BOT_ID", signal: controller.signal });
// When the owning view unmounts:widget.destroy();Older embeds
Embeds that call FluentBotChatWidget.injectWidget("YOUR_BOT_ID") or FluentChatWidget.injectWidget(...) still mount one widget per page. They return no handle, so you can’t call methods or listen to events. FluentChatWidget.destroyWidget() removes that widget. Passing the old signed visitor object throws invalid_configuration.
Replace older embeds with the current install code to use the SDK.
Limitations
- The widget renders in a Shadow DOM. Your site’s CSS doesn’t reach it. Use the channel settings or display options to change its look.
- Display options can’t change behavior. They can’t change instructions, actions, identity, or channel availability.
- One message at a time. Wait for
sendMessage()to resolve before you send another. - Callbacks have limits. Up to 32 tool callbacks with 30 seconds each, and up to 16 forms that load within 10 seconds.
Troubleshooting
Chat is temporarily unavailable.
Possible cause: The loader script didn’t run before the inline script, or mount() rejected. Common reasons are an async or defer attribute on the loader tag, a blocked script, or a disabled channel.
Solution: Remove async and defer from the loader tag, check that the script loads, and turn on the channel’s availability switch in Bot > Channels.
mount() rejects with invalid_configuration
Possible cause: An option has the wrong type, target is missing or not on the page, target is set for bubble or center-stage, or the code passes an option the SDK doesn’t support, such as visitor.
Solution: Compare your options with Mount options and Layouts.
A method throws widget_not_ready
Possible cause: The widget is still starting, or an identify() or logout() call is running.
Solution: Call methods after mount() resolves, and await identity switches.
A Run client-side code action reports it was unsuccessful
Possible cause: No function is registered under the action’s Callback name, it took longer than 30 seconds, or it returned something other than JSON.
Solution: Check getActionReadiness().registered for the exact name, and return a plain JSON result.