Skip to main content
Instance methods enable your code to interact with or modify an active chat instance at run time. They provide a way to programmatically control the behavior and state of the embedded chat component after it has been initialized based on user actions, application logic, or external events.

List of instance methods

The following tables list all supported instance methods, grouped by category.

Message

Message methods allow you to manage and interact with the chat’s message flow in real time. These methods provide functionality for sending messages, navigating through the message list, and updating message history.
Method nameDescription
doAutoScrollScrolls to the most recent message in the list.
scrollToMessageScrolls the messages list to a specific message.
sendSends the specified message to the agent.
updateHistoryUserDefinedUpdates a user_defined property in message history. Need to store the user_defined in the message_state column of the messages table so that it will appear in the history
restartConversationRestarts the conversation with the agent.

User Interface

User Interface methods allow you to control and customize the visual and interactive aspects of the chat component at runtime. These methods help adapt the chat experience to different contexts and user preferences.
Method nameDescription
changeViewChanges the current view state.
updateCustomHeaderItemsUpdates the display of custom menu items that appear in the chat header.
getCustomHeaderItemsRetrieves the current set of custom header items that are configured in the chat widget.
updateLocaleUpdate the display language of the chat.

Char widget state

Chat widget state methods allow you to retrieve and modify the overall state and configuration of the chat widget.
Method nameDescription
getLocaleReturns the current locale that the chat widget uses.

Security and identity

Security and identity methods help maintain secure communication and manage the lifecycle of the chat instance. These methods ensure that user authentication and session integrity are preserved during runtime.
Method nameDescription
updateIdentityTokenReplaces the current JWT with a new one for continued secure communication. This is commonly used when tokens expire or are refreshed during a session.
destroyDestroys the web chat and removes it from the page.

Events

Event methods allow you to subscribe to, manage, and remove event listeners for the chat instance. These methods enable developers to respond to user actions or system events dynamically.
Method nameDescription
onceSubscribes a handler function to an event so it runs only once when that event occurs. After the event fires, the handler is no longer called.
offRemoves a subscription to an event type.
onSubscribes to a type of event.

Details of instance methods

The following sections details the supported instance methods.

getCustomHeaderItems()

The getCustomHeaderItems method retrieves the current set of custom header items that are configured in the chat widget. You can use the output to access and inspect the custom menu items that are currently displayed in the chat header. Example:
console.log(instance.getCustomHeaderItems());

getLocale()

The getLocale method returns the language code for the current language that the chat widget uses, for example, en for English or fr for French. If a region is specified, it returns the language and region codes, for example, pt-BR for Brazilian Portuguese. Example:
console.log(instance.getLocale());

updateCustomHeaderItems(items)

The updateCustomHeaderItems method updates the display of custom items that appear in the chat header. It provides a container for custom items which can be either menu items or dropdown menus. Each item is configurable with a custom callback function that calls when a user select an item. The method accepts an array of objects that define the properties of each custom header item. You can call this method anytime to change the current set of options.
ParameterTypeRequiredDescription
itemsarrayRequiredAn array of custom header items to display. Each item is an object that defines the properties of the header element, including its text, optional icon, alignment, type (menu item or dropdown), and any submenu items if it’s a dropdown.
items[n].idstringRequiredA unique identifier for the header item.
items[n].textstringRequiredThe text to display for the header item.
items[n].alignstringOptionalThe alignment of the header item. Possible values are left or right. Default is left.
items[n].iconstringOptionalA URL or identifier to an icon image to display alongside the text.
items[n].typestringRequiredThe type of header item. Possible values are menu-item or dropdown. Default is menu-item.
items[n].onClickfunctionRequired for menu-item typeA callback function that is called when the button is clicked.
items[n].itemsarrayRequired for dropdown typeAn array of submenu items for the dropdown. Each submenu item is an object with its own properties.
items[n].items[m].idstringRequiredA unique identifier for the submenu item.
items[n].items[m].alignstringOptionalThe alignment of the submenu item. Possible values are left or right. Default is left.
items[n].items[m].textstringRequiredThe text to display for the submenu item.
items[n].items[m].iconstringOptionalA URL to an icon image to display alongside the submenu item text.
items[n].items[m].onClickfunctionRequiredA callback function that is called when the submenu item is clicked. You is responsible for defining this handler.

Design considerations

Availability and form factor constraints
  • Chat header customization is available for fullscreen form factor (1024px+) implementation only.
Item display and overflow behavior
  • The chat header can display a maximum of 3 custom items directly (either menu items or dropdown items).
  • If more than 3 custom items are configured, the exceeding items appear in the chat side panel, between the “New chat” and “Chats” sections.
  • All custom items that you configure are visible in the chat experience (header or side panel).
Layout and alignment
  • Alignment affects text and icon placement within the header, but does not control whether an item appears in the header or the side panel.
Ordering and rendering
  • There is no priority-based ordering for custom items.
  • Items render in the UI in the same order they are defined in the configuration array.
Navigation structure and hierarchy
  • The navigation supports a maximum two-level hierarchy:
    • Level 1: Main menu
    • Level 2: One submenu
  • Deeper nesting is not supported.
  • Each menu level may contain an unlimited number of items.
Example for dropdown:
instance.updateCustomHeaderItems([
  {
    id: 'id',
    text: 'text',
    align: 'right',
    icon: 'https://example.com/example.svg',
    type: 'dropdown',
    items: [
      { 
        id: 'id', 
        text: 'text', 
        align: 'right',
        icon: 'https://example.com/example.svg', 
        onClick: () => {} 
    },
      { 
        id: 'id', 
        text: 'text', 
        align: 'right',
        icon: 'https://example.com/example.svg', 
        onClick: () => {} 
    }
    ]
  }
]);
Example for menu item:
instance.updateCustomHeaderItems([
    {  
        id: 'id',
        text: 'text',
        align: 'left',
        icon: 'https://example.com/example.svg',
        type: 'menu-item',
        onClick: () => {}
    }
]);

updateLocale()

The updateLocale method changes the display language of the chat widget at runtime. By default, the locale is English (en).
ParameterTypeRequiredDescription
localestringRequiredA locale string representing the desired language and region.
The following table lists the supported locale strings:
LanguageLanguage code
Chinese - Traditionalzh-TW
Chinese - Simplifiedzh-CN
Englishen
Frenchfr
Germande
Italianit
Japaneseja
Koreanko
Portuguese - Brazilpt-BR
Spanishes
await instance.updateLocale('ja');

General example

The following example shows how to configure events and instance methods in the embedded web chat:
JavaScript
    <script>
        function preSendHandler(event, instance) {
            console.log('pre:send event', event);
            if (event?.message?.message?.content) {
                event.message.message.content = event.message.message?.content.toUpperCase();
            }
        }

        function sendHandler(event, instance) {
            console.log('send event', event);
        }

        function feedbackHandler(event, instance) {
            console.log('feedback', event);
        }

        function preReceiveHandler(event, instance) {
            console.log('pre-receive event', event);
            event?.message?.content?.map((element) => {
                if (element?.text?.includes('assistant')) {
                    element.text = element.text.replace('assistant', 'Agent');
                }
                element.type = 'user_defined';
            });

            const lastItem = event?.message?.content?.[event.message?.content.length - 1];
            if (lastItem) {
                lastItem.message_options = {
                    feedback: {
                        is_on: true,
                        show_positive_details: false,
                        show_negative_details: true,

                        positive_options: {
                            categories: ['Funny', 'Helpful', 'Correct'],
                            disclaimer: "Provide content that can be shared publicly.",
                        },
                        negative_options: {
                            categories: ['Inaccurate', 'Incomplete', 'Too long', 'Irrelevant', 'Other'],
                            disclaimer: "Provide content that can be shared publicly.",
                        },
                    },
                };
            }
        }

        function receiveHandler(event, instance) {
            console.log('received event', event);
            instance.off('pre:receive', preReceiveHandler);
            instance.updateAuthToken("wrong-or-expired-token")
        }

        function userDefinedResponseHandler(event, instance) {
            console.log('userDefinedResponse event', event);
            event.hostElement.innerHTML = `
                    <cds-code-snippet>
                        node -v Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis,
                        veritatis voluptate id incidunt molestiae officia possimus, quasi itaque
                        alias, architecto hic, dicta fugit? Debitis delectus quidem explicabo vitae
                        laboriosam!
                    </cds-code-snippet>
                    <br><br>
                    <div style="background-color:orange;color:white;padding:10px;">
                        <p>${event.contentItem?.text || '[No message content]'}</p>
                    </div>`;
        }

        function preRestartConversationHandler(event, instance) {
            console.log('pre:restartConversation event', event);
        }

        let calledRestartConversation = false;
        function restartConversationHandler(event, instance) {
            console.log('restartConversationHandler event', event);
            if (!calledRestartConversation) {
                setTimeout(() => {
                    instance.send('Hello from embedded web chat second time')
                }, 3000);
                calledRestartConversation = true;
            }

        }

        function preThreadLoadedHandler(event, instance) {
            console.log('pre:threadLoaded event', event);
            // event.messages[0].content[0].text = 'Modified prompt in thread history';
            event?.messages.forEach((message) => {
                if (message?.sender === 'response') {
                    const [lastItem] = message.content;
                    lastItem.message_options = {
                        feedback: {
                            is_on: true,
                        },
                    };
                    message.message_state = {
                        content: {
                            1: {
                                feedback: {
                                    text: "",
                                    is_positive: true,
                                    selected_categories: []
                                }
                            }
                        }
                    };
                }
            });
        }

        async function authTokenNeededHandler(event, instance) {
            console.log('authTokenNeeded event', event);
            event.authToken = "<Refreshed Token>"
        }

        function onChatLoad(instance) {
            instance.on('chat:ready', (event, instance) => {
                console.log('chat:ready', event);
            });
            instance.once('pre:send', preSendHandler);
            instance.on('send', sendHandler);
            instance.once('pre:receive', preReceiveHandler);
            instance.on('receive', receiveHandler);
            instance.on('feedback', feedbackHandler);
            instance.on('userDefinedResponse', userDefinedResponseHandler);
            instance.on('pre:restartConversation', preRestartConversationHandler);
            instance.on('restartConversation', restartConversationHandler);
            instance.on('pre:threadLoaded', preThreadLoadedHandler);
            instance.on('authTokenNeeded', authTokenNeededHandler);
        }
        window.wxOConfiguration = {
            clientVersion: 'latest',
            orchestrationID: '<tenantId>',
            hostUrl: 'http://localhost:3000',
            showLauncher: true,
            rootElementId: 'root',
            chatOptions: {
                agentId: '<agentId>',
                agentEnvironmentId: '<agentEnvironmentId>',
                onLoad: onChatLoad,
            },
        };
        setTimeout(function () {
            const script = document.createElement('script');
            script.src = `${window.wxOConfiguration.hostUrl}/wxoLoader.js?embed=true`;
            script.addEventListener('load', function () {
                wxoLoader.init();
            });
            document.head.appendChild(script);
        }, 0);
    </script>