Skip to content
This site is under construction. Content, screenshots, and workflows may change at any time.

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

  1. Copy the install code. In Website widget, select Copy install code.

  2. Paste it before </body>. Add it to every page that should show chat. Don’t add async or defer to the first script tag; the inline script needs it loaded first.

  3. 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".

Install code
<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

OptionTypeRequiredDescription
botIdstringYesYour bot ID.
layoutstringNoHow the widget appears. Defaults to bubble. See Layouts.
targetstring or elementFor some layoutsA CSS selector or element to render into. Required for inline, iframe, and help-page; not allowed for the others.
identityTokenstringNoA signed JWT for a signed-in visitor. See Identity verification.
identityCheckingbooleanNotrue hides the widget until you call setIdentityChecking(false). Use it while your page checks whether the visitor is signed in.
optionsobjectNoDisplay overrides for this widget only. See Display options.
userMetadataobjectNoUnsigned JSON, up to 1,000 characters, passed to your form schema handlers as user.user_metadata.
signalAbortSignalNoAborting it cancels a pending mount, which rejects with widget_destroyed.
connection, verifiedConnection, previewToken, appearancestringNoReserved 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

LayoutWhat it showsChannel it uses
bubbleA floating launcher that opens the chat.Chat bubble
center-stageA composer at the bottom center that expands into a conversation card.Center stage
inlineThe chat inside your target element, open on load.Help page
iframeThe chat inside your target element, open on load, with Chat bubble settings.Chat bubble
help-pageThe 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.

Help page inside your page
<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

MethodWhat 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.
Open chat from your own button
document.querySelector("#help-button").addEventListener("click", () => {
window.fluentChatWidget.open();
});

Messages and conversations

MethodWhat 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.

Ask a question for the visitor
const receipt = await window.fluentChatWidget.open({
message: "Where is my order?",
});
console.log(receipt.conversationId);

Context and identity

MethodWhat 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

MethodWhat 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

MethodWhat 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

MemberWhat 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.
idThis widget’s instance ID.
readyA 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();
EventPayloadWhen
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({});
RuleLimit
KeysUp to 16. Each starts with a letter and has up to 64 letters, digits, _, or -.
ValuesStrings up to 512 characters, finite numbers, true, false, or null.
Total size8 KB as JSON.
Reserved keysIdentity 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, and signal.
  • 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 user object with user_metadata (from userMetadata or identify()) and, for a verified visitor, user_id.
  • Return 1 to 20 fields. Each needs a name (letters, digits, and _, up to 40), a label (up to 80 characters), and a type.
  • 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, and pattern, 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.

OptionTypeLimit
displayNamestring100 characters
bubbleTextstring40 characters
footerstring1,000 characters
messagePlaceholderstring100 characters
dismissibleNoticestring500 characters
initialMessagesarray of strings1,000 characters in total
suggestedMessagesarray of strings10 items, 200 characters each
floatingInitialMessages{ enabled, delayMs, oncePerSession }delayMs from 0 to 60000, default 2000; oncePerSession defaults to true
appearanceobjectprimaryColor, secondaryColor, onPrimaryColor, onSecondaryColor, theme (light, dark, auto), headerLogo, botIcon, buttonIcon, buttonAlignment (left, right), headerStyle (solid, gradient, minimal), pictureBorder
centerStageobjecttheme, 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
helpPageobjecttitle, 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);
}
CodeMeaning
bundle_unavailableThe widget script couldn’t load.
invalid_configurationA mount option or method argument isn’t valid.
initialization_failedThe widget couldn’t start.
connection_unavailableThe widget couldn’t connect to FluentChat.
identity_rejectedFluentChat rejected the identity token.
identity_in_progressAn identify() or logout() call is still running.
widget_not_readyThe widget is starting or switching identity.
widget_destroyedThe widget was destroyed, or the mount was aborted.
invalid_listenerThe event name is unknown, or the listener isn’t a function.
invalid_messageThe message is empty, too long, or has unknown fields.
invalid_contextsetContext() input broke a context rule.
message_rejectedFluentChat didn’t accept the message.
message_in_progressAnother message is still being sent or answered.
acceptance_uncertainThe widget couldn’t confirm the message was accepted. Don’t resend it automatically.
reply_failedThe 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 its signal.
  • Wait for sign-in state. Mount with identityChecking: true while you check the session, then call identify() or setIdentityChecking(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.

Next steps