Category

BoldDesk Live Chat Widget JavaScript API Guide

Updated:

You can use the BoldDesk Live Chat Widget JavaScript API to customize and control the chat experience from your website. You can configure visitor information, customize widget behavior, manage chat and ticket fields, automate actions, and respond to widget events. This guide explains how to define visitor details, configure widget behavior, interact with chat fields and ticket fields, manage the widget programmatically, and respond to key lifecycle events.

Configuring Widget Behavior with Live Chat Settings

Place your configuration script above the embedded widget code. These settings determine the widget’s display behavior, prefilled values, form handling, and session persistence.

window['boldChatSettings'] = {
    email: "",
    name: "",
    phoneNo: "",
    maintainIsOpen: true,
    isLauncherVisible: true,
    fields: {
        fieldAPIName: "",
    },
    ticketFields: {
        fieldAPIName: "",
    },
    storageStrategy: "local",
    isWidgetMaximized: false,
};

Prefilling Visitor Details

You can pre-fill user details before initializing the chat. This improves the user experience by eliminating the need for manual entry.

Property Description Example
Email Pre-fills the visitor’s email. If provided, visitors don’t need to enter it manually. The conversation is created using this email once the visitor sends their first message. window['boldChatSettings'] = { email: "[email protected]" };
Name Pre-fills the visitor’s name. Requires an email to be set. window['boldChatSettings'] = { name: "John Doe" };
Phone Number Pre-fills the visitor’s phone number. Requires an email to be set. window['boldChatSettings'] = { phoneNo: "1234567890" };

Managing Sessions for Authenticated Users (Shared Device Behavior)

This pattern supports two outcomes on the same device:

  • Reset chat when a different user logs in
  • Resume chat when the same user logs back in

Managing User Identity Changes

To maintain accurate visitor identification, use your application’s authenticated user identity (email or user ID) as the source of truth. When a user signs in, compare their identifier with the previously stored identifier. If it has changed, clear the existing widget session and apply the new visitor details. If it remains the same, keep the current session and reapply the existing visitor information. This approach helps prevent identity mismatches, especially on shared devices.

Setting Chat Field Values

The fields configuration block allows you to prefill Custom Chat Fields using their Field API Names.

Examples:

window['boldChatSettings'] = { 
    fields: { 
        
        cf_subscriptionType: "Premium", // If the field is a text box 
       
        cf_control: "546",  // If the field is a dropdown (pass the option ID)
        
        cf_framework: ["552", "553"], // If the field is a multi-select dropdown (pass an array of option IDs)
        
        cf_resolved: "false"   // If the field is a radio button (pass the value as string)
    }
};

To find the Field API Name, navigate to: Admin → Chat → Fields → Chat Fields

Chat field.png

Populating Ticket Fields on the Offline Form

Use the ticketFields block to prefill Custom Ticket Fields shown when the offline contact form appears. This applies only when the offline form type is set to Contact Form with ticket fields.

When visitors are contacting outside of business hours, the offline form is displayed. Prefilling using the ticketFields property is only supported when the form type is set to “Contact Form with ticket fields”.

window['boldChatSettings'] = { 
    ticketFields: { 
        
        cf_subscriptionType: "Premium", // If the field is a text box 
       
        cf_control: "570",  // If the field is a dropdown (pass the option ID)
        
        cf_framework: ["571", "572"], // If the field is a multi-select dropdown (pass an array of option IDs)
        
        cf_resolved: "false"   // If the field is a radio button (pass the value as string)
    }
};

To find the Field API Name, navigate to: Admin → Help Desk → Fields and Forms → Ticket Fields

Ticket fields.png

The prefilled values in the custom ticket fields are displayed as shown in the image below.

Ticketfield.png

Persistence and Visibility Controls

  • maintainIsOpen:

This setting determines whether the chat window remains open across different browser tabs and reloads.

  • true (default): The chat window state persists across tabs and page reloads.

  • false: Each tab operates independently and resets upon page reload.

    window['boldChatSettings'] = { maintainIsOpen: false };
    

isLauncherVisible:

This setting controls the visibility of the chat launcher button.

  • true (default): The chat launcher button is visible.
  • false: The launcher button is hidden.
    window['boldChatSettings'] = { isLauncherVisible: false };
    

storageStrategy:

This setting controls how the chat session data is stored across page reloads and browser tabs.

  • cookie (default): Session data is stored using cookies. This allows basic session persistence but may have limitations across tabs or based on cookie policies.

  • local: Session data is stored using localStorage, which allows persistence across page reloads and browser tabs.

  • none: No session data is stored. Each page reload starts a new session, and previous chat history is not retained.

    window['boldChatSettings'] = { storageStrategy: 'local' };
    

isWidgetMaximized:
This setting controls the maximized state of the chat messenger popup.

  • false (default): The chat messenger popup appears in a minimized state.
  • true: The chat messenger popup appears in a maximized state.
    window['boldChatSettings'] = { isWidgetMaximized: true };
    

Managing the Widget with $boldChat Methods

The following methods allow dynamic control over the chat widget.
Before using any chat widget methods, ensure that $boldChat is properly initialized as an array:

window.$boldChat = window.$boldChat || [];

Controlling Message Input (set:canSend)

Enable or disable the visitor’s ability to send messages:

window.$boldChat.push(["set:canSend", false]); // Disable message sending
window.$boldChat.push(["set:canSend", true]);  // Enable message sending

Clearing a Chat Session (do:clearSession)

Resets the chat session by clearing messages, cookies, and local storage. Explore further instructions about How to Add a Clear Session Option to the Live Chat Widget.

window.$boldChat.push(["do:clearSession"]);

Adding Custom Menu Options (do:addOption)

Add custom actions, displayed in the widget’s “More Options” menu. Learn more about How to Add a Clear Session Option to the Live Chat Widget.

window.$boldChat.push(["do:addOption", "Clear Session"]);

Opening and Closing the Messenger (do:setIsOpen)

Controls whether the chat messenger popup is open or closed.

window.$boldChat.push(["do:setIsOpen", true]);  // Open the chat messenger popup
window.$boldChat.push(["do:setIsOpen", false]); // Close the chat messenger popup

Showing or Hiding the Entire Widget (do:setIsVisible)

Controls the visibility of the entire chat widget, including the launcher and messenger.

window.$boldChat.push(["do:setIsVisible", true]);  // Show the chat widget
window.$boldChat.push(["do:setIsVisible", false]); // Hide the chat widget

Control Widget Section Navigation (do:openSection)

By default, the chat widget loads its chat section automatically. However, you can use the code below to programmatically navigate to a help section.

window.$boldChat.push(["do:openSection", "help"]); // Navigate to the help section if knowledge base is enabled

Available Sections

Section Description
home Displays an overview of recent conversations, announcements, and knowledge base articles.
help Knowledge base and article browsing area.
conversation Live chat and conversation-related experiences.

Verify Session (do:sessionVerification)

Use the do:sessionVerification method to verify an unverified chat session by passing a valid userToken and email. This ensures the current session is securely associated with an authenticated user.

window.$boldChat.push(["do:sessionVerification", {
    email: "[email protected]",
    userToken: "jwt-token",
    callback: (res) => {
        //code to be executed after session verified.
    }
}]);

For detailed information about session verification, JWT authentication requirements, verification responses, fallback behavior, and complete implementation examples, see the Session Verification with Custom JavaScript article.

Event Listeners for Dynamic Interaction

The Live Chat Widget provides a flexible event system that enables real‑time validation, custom UI behaviors, internal workflows, and conversation tracking.
You can use the following event listeners to handle specific user interactions within the chat widget:

  • validateForm – Handles form validation before starting a conversation.
  • moreOptionClick – Handles interactions with the “More Options” menu.
  • beforeEmailSubmit - Handles email submission before starting a conversation and on workflow email submit.
  • conversationStarted - Fired when a new chat conversation is successfully created and initiated.
  • conversationClosed - Fired when the active chat conversation is closed by either the customer or the agent.
  • widgetOpened – Triggered when the chat widget is opened by the user.
  • widgetClosed – Triggered when the chat widget is closed by the user.
  • unreadConversationCountChanged – Triggered when the unread conversation count changes in the widget.
  • chatServerConnected – Triggered when the widget successfully establishes a connection with the chat server.
  • chatServerDisconnected – Triggered when the widget loses connection to the chat server.
  • widgetLoaded – Triggered when the widget has finished loading and is ready for interaction.
  • widgetViewChanged – Triggered whenever the widget navigates between sections or views, including Home, Help, Conversation, Article List, Article Details, Offline Form, and Conversation List.

Before using these event listeners, ensure that $boldChat is properly initialized:

window.$boldChat = window.$boldChat || [];

Validating Forms Before Conversation Creation (on:validateForm)

This event listener is used for form validation before allowing a user to start a conversation.

  1. Register the event listener:

    window.$boldChat.push(["on:validateForm", onValidate]);
    
  2. Define the validation function: The function should return a Promise resolving to an object that indicates whether the form is valid.

    <script type="text/javascript">
        window.$boldChat = window.$boldChat || [];
        window.$boldChat.push(["on:validateForm", onValidate]);
    
        function onValidate(formData) {
            return new Promise((resolve) => {
                var response = { isValid: false, confirmationMessage: "User is not a valid user." };
                resolve(response);
            });
        }
    </script>
    
  3. The function should return an object in the following format:

    { 
        isValid: boolean, 
        confirmationMessage: string
    }
    
    • If isValid is true, a conversation will be created, and the confirmationMessage will be posted on behalf of the agent. If empty, the system will use the default admin-configured message.
    • If isValid is false, no conversation will be created, and the confirmationMessage will be shown in the chat to alert the user regarding invalid form submission.

Handling Custom Option Clicks (on:moreOptionClick)

Triggers specific actions when a user selects an option from the “More Options” menu.

  1. Register the event listener:

    window.$boldChat.push(["on:moreOptionClick", onMoreOptionClick]); 
    
  2. Define the function to handle user actions: You can define custom logic to handle each selection and execute specific tasks accordingly.

        <script type="text/javascript" >
        window.$boldChat = window.$boldChat || [];
        window.$boldChat.push(["on:moreOptionClick", onMoreOptionClick]);
    
        function onMoreOptionClick(item) {
            if(item.name === "Clear Session") {
                window.$boldChat.push(["do:clearSession"]);
            }
        }
        </script> 
    

This JavaScript API allows seamless customization of the Live Chat Widget by enabling developers to manage user data, control widget behavior, and respond to user interactions dynamically.

Email Validation Before Submission (on:beforeEmailSubmit)

Triggers specific actions when a user enters an email in the pre-chat form or submits email via workflow.

  1. Register the event listener:

    window.$boldChat.push(["on:beforeEmailSubmit", onBeforeEmailSubmit]); 
    
  2. Define the before email submit function; this function will be triggered and executed when an email is submitted in the pre-chat form or via workflow.

    <script type="text/javascript" >
       window.$boldChat = window.$boldChat || [];
       window.$boldChat.push(["on:beforeEmailSubmit", onBeforeEmailSubmit]);
    
       async function onBeforeEmailSubmit(email) {
           console.log("Submitted Email: ", email);
           var isValid = // write your code to validate email.
           var response = { isValid: isValid, confirmationMessage: "The given email is not a business mail."}
           return response;
       }
    </script> 
    
  3. If required, the function may return an object in the following format:

     ```json
     { 
         isValid: boolean, 
         confirmationMessage: string
     } 
     ```
    
    • If isValid is true, a conversation will be created.
    • If isValid is false, conversation will not be created, and the confirmationMessage will be shown in the error notification message.
    • If the function does not return an object, the existing flow continues and conversation is created as usual.

Tracking Conversation Start (on:conversationStarted)

This event fires when BoldDesk successfully creates a conversation.

window.$boldChat.push(["on:conversationStarted", async (context) => {
 // Update in-page indicators, start analytics timers, etc.
}]); 

Useful for analytics, routing feedback, or UI effects.

Tracking Conversation Closure (on:conversationClosed)

Triggered when the visitor or agent closes a conversation:

window.$boldChat.push(["on:conversationClosed", async (context) => {
// Reset UI, update counters, finalize logs
}]); 

Ideal for lifecycle management and user experience consistency.

Tracking Widget Opened (on:widgetOpened)

Triggered when the user opens the chat widget.

window.$boldChat.push(["on:widgetOpened", () => {
    // Initialize custom UI components, start engagement tracking,
    // or display contextual messages when the widget becomes active.
}]);

Ideal for initializing user interactions and tracking widget engagement.

Tracking Widget Closed (on:widgetClosed)

Triggered when the user closes the chat widget.

window.$boldChat.push(["on:widgetClosed", () => {
    // Save widget state, stop active timers,
    // or remove temporary UI elements before closing.
}]);

Ideal for cleanup activities and preserving session information.

Tracking Unread Conversation Count Changes (on:unreadConversationCountChanged)

Triggered when the unread conversation count changes in the widget.

window.$boldChat.push(["on:unreadConversationCountChanged", (msgCount) => {
    // Update notification badges, refresh unread message indicators,
    // or synchronize the latest unread count with external applications.
}]);

Ideal for managing notifications and unread message tracking.

Tracking Chat Server Connection (on:chatServerConnected)

Triggered when the widget successfully establishes a connection with the chat server.

window.$boldChat.push(["on:chatServerConnected", () => {
    // Enable chat-related functionality, update connection status indicators,
    // or resume operations that require an active server connection.
}]);

Ideal for handling successful connections and restoring chat functionality.

Tracking Chat Server Disconnection (on:chatServerDisconnected)

Triggered when the widget loses connection to the chat server.

window.$boldChat.push(["on:chatServerDisconnected", () => {
    // Display offline status, pause actions that depend on connectivity,
    // or prepare pending operations for retry after reconnection.
}]);

Ideal for connection monitoring and graceful error handling.

Tracking Widget Loaded (on:widgetLoaded)

Triggered when the widget has finished loading and is ready for user interaction.

window.$boldChat.push(["on:widgetLoaded", () => {
    // Initialize custom functionality and apply widget configurations
    // after the widget has fully loaded. 
}]);

Ideal for initializing custom logic, and configuring the widget once it is ready.

Tracking Widget View Changes (on:widgetViewChanged)

Triggered when the widget navigates between sections or views, such as Home, Help, Conversation, Article List, Article Details, Offline Form, or Conversation List views.

window.$boldChat.push(["on:widgetViewChanged", (details) => {
    handleWidgetViewChanged(details);
}]);

The callback receives an object containing information about the navigation transition.

Property Description
previousSection The section the user was viewing before navigation.
currentSection The section currently being displayed.
previousView The view the user was on before navigation.
currentView The view currently being displayed.

Available Sections

Section Description
home Displays an overview of recent conversations, announcements, and knowledge base articles.
help Knowledge base and article browsing area.
conversation Live chat and conversation-related experiences.

Available Views

View Description
allCategoriesListView Displays all available categories.
articleDetailsView Displays the content of a selected article.
articleListView Displays articles within a selected category.
conversationListView Displays the list of conversations.
conversationView Active conversation/chat view.
homeView Widget home page.
offlineFormView Displays the offline contact form when agents are unavailable.
satisfactionFeedbackView Collects feedback for knowledge base articles.
satisfactionSurveyView Displays the post-conversation satisfaction survey.
workflowContactFormView Displays a workflow contact form.

Example: Update the Conversation List Button Text

In this example, the default “New Conversation” button text is changed to “Chat with us” when the user navigates to the Conversation List view.

function handleWidgetViewChanged(details) {
    if (
        details.currentSection === "conversation" &&
        details.currentView === "conversationListView"
    ) {
        const host = document.querySelector("#boldchat-host");

        if (!host || !host.shadowRoot) {
            return;
        }

        const conversationListFooter =
            host.shadowRoot.querySelector(".bc-conversation-list-footer");

        const conversationInitiationBtn =
            conversationListFooter?.querySelector("#bc-btn-container");

        const buttonTextElement =
            conversationInitiationBtn?.querySelector(".btn-text");

        if (!buttonTextElement) {
            return;
        }

        // Update button text
        buttonTextElement.innerHTML = "Chat with us";
    }
}

Ideal for customizing view-specific UI elements based on the user’s current navigation state.

Example: Perform Actions Based on Navigation Path

The previousSection and previousView properties can be used to execute logic only when users navigate from a specific location.

In this example, copy, cut, and paste actions are disabled in the message input box only when the user enters the Conversation View from the Home section.

function handleWidgetViewChanged(details) {
    if (
        details.previousSection === "home" &&
        details.currentSection === "conversation" &&
        details.currentView === "conversationView"
    ) {
        const host = document.querySelector("#boldchat-host");

        if (!host || !host.shadowRoot) {
            return;
        }

        const textarea =
            host.shadowRoot.querySelector("#bc-msg-input");

        // Prevent copy, paste, and cut actions
        textarea?.addEventListener("paste", (e) => e.preventDefault());
        textarea?.addEventListener("copy", (e) => e.preventDefault());
        textarea?.addEventListener("cut", (e) => e.preventDefault());
    }
}

In this scenario, the restrictions are applied only when the user navigates from the Home section to the Conversation View. If the user opens the same view from another section or conversation flow, the behavior remains unchanged.

Ideal for implementing navigation-based customizations, conditional UI updates, and view-specific business logic.

Permission to Configure Live Chat Widget Behavior

For configuring Live Chat Widget behavior, you must have the Manage Settings permission enabled.

Manage Settings.png

Troubleshooting

  1. Prefilled ticketFields are not appearing on the offline form

    • Confirm the offline form type is set to Contact Form with ticket fields.
    • Confirm each key in boldChatSettings.ticketFields matches the Ticket Field API Name (Admin > Help Desk > Fields and Forms > Ticket Fields).
  2. Prefilled name or phone number is not applied
    Confirm boldChatSettings.email is set. The documented behavior requires email to be present before name or phoneNo are applied.

  3. Session does not persist as expected

    • Confirm boldChatSettings.storageStrategy is set to the intended value (cookie, local, or none).
    • If storageStrategy is none, each reload starts a new session by design.
  4. Chat remains tied to the previous user on shared devices

    • Use an application-level identifier check (email/user ID).
    • Call ["do:clearSession"] when the authenticated user changes, then apply the new boldChatSettings identity values.

Frequently Asked Questions

  1. Does the widget support asynchronous validation in lifecycle events?
    Yes. All major events including on:validateForm and on:beforeEmailSubmit support async handlers, allowing you to apply business rules before a conversation begins.

  2. Is it possible to disable the message input while running checks?
    Yes. Use ["set:canSend", false] to pause message sending and re-enable it once your logic finishes.

  3. How do Chat Fields differ from Ticket Fields in the widget?
    Chat Fields appear within the chat workflow, while Ticket Fields populate the offline contact form. Ticket Fields require the Contact Form with ticket fields setting.

  4. Can I track when conversations start and end for reporting?
    Yes. Use the new on:conversationStarted and on:conversationClosed events to record timestamps, update the UI, or implement analytics logic.

  5. How do I fully reset a user’s session?
    Call ["do:clearSession"] manually or via a custom menu option triggered in on:moreOptionClick.

  6. Can I hide the launcher but still open the chat programmatically?
    Yes. Set isLauncherVisible: false and call ["do:setIsOpen", true] when needed.

  7. How can I ensure that every visit to my website is treated as a new chat session, even if the same user revisits multiple times?
    To treat every visit as a new chat session, disable session storage in the chat widget. This prevents the system from remembering previous users or conversations.

    Use this setting:

    window['boldChatSettings'] = {
      storageStrategy: 'none'
    };
    
  8. How can I verify a chat session after a user signs in?
    Use the do:sessionVerification method and provide a valid email address and JWT token. This securely associates the current chat session with an authenticated user without requiring the widget to be reloaded.

  9. What happens if session verification fails?
    If the provided email or JWT token is invalid, the session verification request will fail and the current session will remain unchanged. You can use the callback response to handle verification failures and display appropriate messages to users.

  10. Can I customize the widget UI after it finishes loading?
    Yes. Use the on:widgetLoaded event to execute custom logic once the widget is fully initialized. This is useful for updating widget text, applying branding changes, or modifying elements within the widget.

  11. Can I detect when users open or close the chat widget?
    Yes. Use the on:widgetOpened and on:widgetClosed events to track widget usage, start or stop timers, update analytics, or perform custom UI actions.

  12. How can I monitor unread conversation counts in the widget?
    Use the on:unreadConversationCountChanged event. The callback provides the latest unread conversation count, allowing you to update notification badges or synchronize counts with external applications.

  13. Can I track the widget’s connection status with the chat server?
    Yes. Use the on:chatServerConnected and on:chatServerDisconnected events to monitor connectivity, update status indicators, or handle temporary connection interruptions.

  14. How can I detect when users navigate between widget pages?
    Use the on:widgetViewChanged event. The callback provides the previous and current section and view information, allowing you to apply custom logic based on navigation changes.

  15. Can I customize specific widget views based on navigation events?
    Yes. The on:widgetViewChanged event can be used to identify the currently displayed view and modify related UI elements, such as updating button labels, changing content, or applying custom styling.

  16. Can I perform actions only when users navigate from a specific page?
    Yes. The previousSection, currentSection, previousView, and currentView properties in the on:widgetViewChanged event allow you to execute logic only for specific navigation paths within the widget.

Related Articles

  1. How to Launch the Bold Chat Widget with an External Button
  2. How to Add a Clear Session Option to the Live Chat Widget
Was this article useful?
Like
Dislike
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied
Access denied
Access denied

No articles or sections found
No articles or sections found