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.
updateLocaleChanges the display language. Supported language codes include: de (German), en (English), es (Spanish), fr (French), it (Italian), ja (Japanese), and pt-BR (Portuguese - Brazil).

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.

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>