Skip to main content

Chat Widget: Integrate Your Agent into Web Application

Integrate your Flametree AI agent into any website with a powerful, customizable React chat widget. This widget provides seamless real-time chat functionality with extensive customization options and support for both floating and embedded deployment modes.


Prerequisitesโ€‹

  • Access to Flametree platform
  • A configured AI agent
  • Website with ability to edit HTML/add custom code
  • Basic understanding of HTML and JavaScript

Featuresโ€‹

  • ๐Ÿ’ฌ Real-time messaging - Instant chat functionality
  • ๐ŸŽค Audio recording - Voice message support with playback
  • ๐Ÿ—ฃ๏ธ Speech-to-text - Convert voice to text automatically
  • ๐Ÿ”Š Text-to-speech - Voice-over capabilities for accessibility
  • ๐ŸŽฏ Flexible deployment - Floating button or embedded widget
  • ๐Ÿ“ฑ Responsive design - Optimized for all device sizes
  • โŒจ๏ธ RTL support - Right-to-left text compatibility
  • ๐Ÿ”„ Session management - Persistent conversation history
  • ๐ŸŽจ UI customization - Extensive styling options

Widget Typesโ€‹

The widget supports two deployment modes:

ModeDescriptionUse Case
FloatingDisplays as a floating button that opens a modal chat windowCustomer support, help desk
EmbeddedOccupies full width/height of parent containerDedicated chat pages, integrated experiences

Integration Setupโ€‹

Step 1: Get the Widget Codeโ€‹

  1. Navigate to Your Agent

    • Open the Flametree portal
    • Go to the Agents section
    • Click on the agent you want to configure
  2. Locate the HTML Code Section

    • On the right-hand configuration panel, scroll down to the HTML Code section
    • Next to the HTML Code label, you'll see two icon buttons:
      • ๐Ÿ‘ View โ€” to preview the code
      • ๐Ÿ“‹ Copy โ€” to copy the code to clipboard
  3. Copy the Widget Code

    • Click the Copy (๐Ÿ“‹) icon to copy the generated HTML snippet

Step 2: Add Widget to Your Websiteโ€‹

  1. Insert the Code

    • Paste the copied snippet at the end of your page, just before the closing </body> tag
    • For website builders (Tilda, Webflow, Wix, WordPress), paste into the custom HTML or script section
  2. Alternative Manual Setup

    • Add container element: <div id="chat-widget"></div>
    • Include widget script: <script src="<PortalLink />/public-storage/widget/bot-chat-widget.umd.js"></script>
    • Initialize widget with configuration
    warning

    If the widget is embedded, make sure to set a fixed height on the container element (for example, <div id="chat-widget" style="height: 600px">). Without it, the container will grow with each new message instead of scrolling, making the chat unusable

Make sure:

  • The code is placed before the closing </body> tag
  • The website allows external scripts
  • There are no JavaScript errors in the browser console

Step 3: Test the Integrationโ€‹

  1. Reload Your Website

    • The chat button should appear (floating mode) or widget should load (embedded mode)
  2. Test Functionality

    • Click the chat button or interact with embedded widget
    • Send a test message to verify agent response
    • Test voice features if enabled

If the widget does not respond, verify that:

  • the agent is active and not in error state
  • botRoute and authorizationToken are correct
  • the agent is properly configured

Configuration Optionsโ€‹

Required Parametersโ€‹

ParameterTypeDescription
botRoutestringAPI endpoint URL for the chat bot
authorizationTokenstringAuthorization token for API requests

Core Settingsโ€‹

ParameterTypeDefaultDescription
elementIdstring'chat-widget'HTML element ID for widget mounting
userIdstring''Unique customer identifier
userNamestring'Guest'Display name for the customer
emailstring''Customer's email address
phonestring''Customer's phone number
tip

You can use multiple widgets on the same page by setting different elementId values

Appearance & Behaviorโ€‹

ParameterTypeDefaultDescription
isFloatingBtnbooleanfalseEnable floating button mode
primaryColorstring#ff613ePrimary theme color
openByDefaultbooleanfalseAuto-open chat on load
openByDefaultDelaynumber3000Delay in milliseconds for auto-open chat on load. Min value: 1000
headerTitlestring'Chat with the Agent'Chat header title
headerTitleColorstring'#000000'Header title color
showPoweredBybooleantrueShow Powered by footer
showAiBotTimestampbooleanfalseShow response timestamps next to AI agent messages. By default, timestamps are automatically displayed only for customers and human operators (including copilot drafts).
showAgentAvatarbooleanfalseShow AI agent avatar icon next to its messages. Disabled by default for a cleaner UI.
usePlainChatbooleantrueEnable ChatGPT-like plain text design for the chat widget without gray message bubbles. Enabled by default.
showVoiceOverbooleanfalseDisplays the Voice over toggle in the widget. When true, customers can toggle automatic audio playback for all assistant messages. When false, the toggle is hidden, and audio playback is manual via the speaker icon under each message.

ย ย ๐Ÿ’ก Tip: to provide a standard GPT-like interaction pattern, keep this set to false (default). This hides the global automatic playback toggle, ensuring audio is only played when the customer explicitly clicks the speaker icon under a specific message.
voiceOverbooleanfalseEnable text-to-speech
disableStreamingTtsbooleanfalseControls how TTS audio is synthesized for bot replies. By default, the widget streams audio in chunks as the bot reply is being generated, so playback can start before the message is fully written. When true, this incremental synthesis is disabled โ€” the full reply is synthesized in a single pass after the bot finishes typing, then played back as one audio segment. Useful when chunked synthesis produces audible seams or unnatural prosody, at the cost of a longer wait before audio starts. Has no effect unless the agent has text-to-speech enabled.

ย ย ๐Ÿ’ก Tip: enable this if you notice audible seams, clicks, or unnatural pauses between TTS chunks. Keep it false (default) when you want audio to start playing as early as possible โ€” for example, in voice-first or hands-free scenarios where reducing perceived latency matters more than seamless prosody.
timezonestring''IANA timezone for message timestamps (for example, 'Europe/Madrid', 'America/New_York'). Defaults to the browser's local timezone.

ย ย โ„น๏ธ Note: use this when the widget is embedded in an environment where the browser timezone may differ from the desired display timezone โ€” for example, a kiosk, an internal tool with a fixed locale, or a server-side-rendered page.

Floating Button Customizationโ€‹

ParameterTypeDefaultDescription
floatingBtnSizenumber58Button size in pixels
floatingBtnOpennedIconUrlstring''Custom open icon URL
floatingBtnClosedIconUrlstring''Custom closed icon URL
floatingBtnIconClosedSizenumber58Closed icon size
floatingBtnIconOpenedSizenumber32Open icon size
floatingBtnMarginBottomnumber8Bottom margin
floatingBtnMarginRightnumber16Right margin
floatingBtnMobileMarginBottomnumber8Mobile bottom margin
floatingBtnMobileMarginRightnumber16Mobile right margin
floatingBtnIconShapecircle, squarecircleShape variant of the default floating button icon
floatingBtnIconBackgroundColorstring#FB8535Background color of the default floating button icon
floatingBtnClosedIconColorstring#FFFFFFInner icon stroke/fill color of the default floating button icon

Advanced Optionsโ€‹

ParameterTypeDefaultDescription
disableSendingMessageWhileAwaitingResponsebooleanfalsePrevent messages during bot response
onError(error: Error) => voidโ€“Error handling callback
avatarUrlstring''Custom agent avatar URL
tooltipTextstring''Floating button tooltip
giftTextstring''Gift button text
giftLinkstring''Gift button URL
multiAgentbooleanfalseEnable multi-agent support
versionstring'v1'Widget version
kwargsobject'{}'Custom variables to pass when starting a session. Variables starting with _ will not be logged or passed to the agent's prompt.
messageListenersArray<(message) => void>undefinedList of callbacks that track chat message events
showStartNewSessionBtnbooleanfalseShows a button next to the chat input to start a new session. Hidden during audio recording

Start New Session Buttonโ€‹

When showStartNewSessionBtn is set to true, a button appears to the right of the chat input. Selecting this button triggers the following sequence:

  1. Sends a DELETE /session/{id} request to close the current session. Errors are ignored, and the restart proceeds.
  2. Clears the message list immediately to display the typing indicator.
  3. Skips the session history check and creates a new session directly.
  4. Disables the button until the greeting from the new session arrives.
info

The button tooltip displays Start new conversation. While waiting for the new session to start, the button is visually disabled (opacity: 0.4) and non-interactive to prevent duplicate session creation.

Customer ID Managementโ€‹

The userId parameter follows this priority order:

  1. Explicitly provided in widget parameters
  2. Retrieved from localStorage (flametree-widget-userId-v2)
  3. Auto-generated and saved to localStorage if not provided (when userId is empty)

Operation Modesโ€‹

The widget supports three distinct operation modes

Mode 1: Standard Chat (version: 'v1')โ€‹

  • Creates new session on initialization
  • No chat history retrieval
  • Simple, straightforward chat experience

Mode 2: Session Management (version: 'v2', multiAgent: false)โ€‹

  • Retrieves all active customer sessions on initialization based on customer ID
  • Continues existing session if botRoute matches
  • Creates new session if no match found
  • No agent selection screen

Mode 3: Multi-Agent (version: 'v2', multiAgent: true)โ€‹

  • Displays all active customer sessions
  • Shows agent selection screen
  • Allows switching between different agent conversations
  • Supports multiple sessions per agent

Implementation Examplesโ€‹

Basic Floating Chatโ€‹

BotChatWidget.createBotChat({
botRoute: 'https://api.example.com/bot',
authorizationToken: 'your-auth-token',
elementId: 'chat-widget',
isFloatingBtn: true,
primaryColor: '#007bff',
});

Embedded Chat with Voice Featuresโ€‹

BotChatWidget.createBotChat({
botRoute: 'https://api.example.com/bot',
authorizationToken: 'your-auth-token',
elementId: 'embedded-chat',
isFloatingBtn: false,
showVoiceOver: true,
voiceOver: true,
headerTitle: 'AI Assistant',
});

Advanced Multi-Agent Setupโ€‹

BotChatWidget.createBotChat({
// Required
botRoute: 'https://api.example.com/bot',
authorizationToken: 'your-auth-token',

// Multi-agent configuration
version: 'v2',
multiAgent: true,

// Customization
elementId: 'chat-widget',
userId: 'user123',
userName: 'John Doe',
email: 'john@example.com',
isFloatingBtn: true,
primaryColor: '#ff613e',
openByDefault: false,

// UI Customization
headerTitle: 'Support Center',
headerTitleColor: '#ffffff',
showPoweredBy: false,
avatarUrl: 'https://example.com/bot-avatar.png',
showAiBotTimestamp: false, // Hidden by default for AI, but visible for humans

// Floating button
floatingBtnSize: 64,
floatingBtnOpennedIconUrl: '',
floatingBtnClosedIconUrl: '/icons/floating_icon_message.svg',
tooltipText: 'Need help? Chat with us!',

// Features
showVoiceOver: true,
voiceOver: true,
disableSendingMessageWhileAwaitingResponse: true,

// Gift feature
giftText: 'Send Gift ๐ŸŽ',
giftLink: 'https://example.com/gifts',

// Error handling
onError: (error) => {
console.error('Chat widget error:', error);
// Custom error handling logic
}
});

External Widget Methodsโ€‹

The widget exposes several optional helper methods that allow external scripts on your website to control the widget programmatically. These methods become available on the global window object after the widget is initialized.

Available Methods

// Open a specific session by ID (v2 mode)
window.BotChatWidget.openSession(sessionId: string): void;

// Programmatically open the chat widget
window.BotChatWidget.openChat(): void;

// Update session parameters for the currently active session.
// Example payload:
// {
// env_info: {
// _party_id: "123",
// _session_id: "123",
// customKey: "value",
// ...
// }
// }
window.BotChatWidget.updateSession(data: object): void;

// Action trigger for sending an optional message in a chat widget
window.BotChatWidget.runAction(message: string): void;

// Starts a new chat session in the widget
window.BotChatWidget.startNewSession(): void;

When to Use These Methods

  • Refreshing expiring tokens. Call updateSession() to pass updated session kwargs without restarting the session.
  • Deep-linking into conversations. Use openSession() to jump directly to a specific chat session.
  • Opening the widget from your UI. Attach openChat() to buttons, menus, or onboarding flows.
  • Sending an action message to the widget. Use runAction() to initiate an action message in the active chat session.
  • Starting a new conversation session. Use startNewSession() to create a new chat session in the widget.

Widget Message Handling (Custom Events from Agent)โ€‹

The widget can receive custom messages from the agent over the WebSocket connection and use them to trigger JavaScript actions in the host application. When such a message arrives, the widget identifies the analytics provider, determines the event name, and invokes the appropriate client-side handler.

A custom message includes the analytics provider, the event name, and optional data. Based on this information, the widget identifies the provider, reads the event name, and runs the corresponding client-side action.

important

Custom WebSocket messages must include the field type: custom so the widget can distinguish them from system or internal messages.

A custom message uses the following format:

   {
"type": "custom",
"provider": "string",
"event": "string",
"data": {}
}
ParameterDescription
typeMust always be custom for custom event messages
providerTarget analytics provider, such as Google or Meta
eventEvent name that the widget should trigger, for example submitForm
dataObject with arbitrary fields, for example submitted form data. May be empty

When the widget receives this message, it reads the type, provider and event name, then calls the matching client-side handler. For example, if the provider is Google Analytics, the widget adds a new entry to dataLayer.

Testing Your Integrationโ€‹

  1. Verify Widget Appearance

    • Check if floating button appears (floating mode)
    • Verify embedded widget loads correctly (embedded mode)
  2. Test Basic Functionality

    • Click the chat button or interact with widget
    • Send a test message like: Hello, what services do you offer?
    • Verify the agent responds appropriately
  3. Test Advanced Features

    • Voice messages (if audio recording enabled)
    • Text-to-speech playback (if voiceOver enabled)
    • Multi-agent switching (if multiAgent enabled)

    If voice features do not work, verify that:

    • the browser supports audio recording
    • microphone permissions are granted
    • the website is served over HTTPS
    • voice capabilities are enabled in the agent

Browser Storageโ€‹

localStorageโ€‹

KeyPurpose
flametree-widget-userId-v2Auto-generated user ID when not explicitly provided
unreadConversationsArray of unread conversation IDs

sessionStorageโ€‹

KeyPurpose
flametree-widget-defaultAuthorizationTokenInitial authorization token
flametree-widget-authorizationTokenCurrent active token (updated in multi-agent mode)
flametree-widget-defaultBotRouteInitial bot route URL
${botRoute}-sessionIdActive session ID for specific agent

Browser Supportโ€‹

The Flametree Chat Widget is compatible with all modern browsers that support:

  • ES6+ JavaScript features
  • MediaRecorder API (for audio recording)
  • Local/Session Storage
  • CSS Grid and Flexbox

Supported Browsers:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Security Considerationsโ€‹

  • Protect authorization tokens. Do not expose them in client-side code or public repositories
  • Rotate tokens if they are compromised
  • Monitor widget usage for suspicious activity
  • Handle customer data according to your privacy policy and applicable regulations
  • Obtain customer consent before enabling voice recording

Was this article helpful?