Chat state
Chat widget state methods allow you to retrieve and modify the overall state and configuration of the chat widget.| Method name | Description |
|---|---|
getLocale | Returns the current locale that the chat widget uses. |
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.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 name | Description |
|---|---|
doAutoScroll | Scrolls to the most recent message in the list. |
loadThreadById | Loads an existing conversation thread by its ID. |
restartConversation | Restarts the conversation with the agent. |
scrollToMessage | Scrolls the messages list to a specific message. |
send | Sends the specified message to the agent. |
updateMessageStateUserDefined | Updates a user_defined property in message state for persistence across thread reloads. |
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 name | Description |
|---|---|
destroy | Destroys the chat and removes it from the page. |
updateAuthToken | Replaces the current JWT with a new one for continued secure communication. |
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 name | Description |
|---|---|
changeView | Changes the current view state of the chat widget. |
getCustomHeaderItems | Retrieves the current set of custom header items that are configured in the chat widget. |
updateCustomHeaderItems | Updates the display of custom menu items that appear in the chat header. |
updateWelcomeScreen | Updates home screen elements including welcome message, description, starter prompts, timestamp, and agent icon. |
updateLocale | Updates the display language of the chat. |
Complete example
The following example demonstrates how to configure events and instance methods in the embedded chat:<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);
}
async function feedbackHandler(event, instance) {
console.log('feedback', event);
// Send silent message for negative feedback
if (!event.is_positive) {
const feedbackComment = event.comment ? `: ${event.comment}` : '';
const systemMessage = `User submitted negative feedback${feedbackComment}`;
await instance.send(systemMessage, { silent: true });
}
}
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);
}
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.
</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 chat second time');
}, 3000);
calledRestartConversation = true;
}
}
function preThreadLoadedHandler(event, instance) {
console.log('pre:threadLoaded event', event);
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>";
}
async function viewPreChange(event, instance) {
console.log('viewPreChange event', event);
document.body.classList.add('chat-view-changing');
}
async function viewChange(event, instance) {
console.log('viewChange event', event);
console.log('View changed from', event.oldViewState, 'to', event.newViewState);
}
function onChatLoad(instance) {
instance.on('chat:ready', (event, instance) => {
console.log('chat:ready', event);
// Add custom header items
const ICONS = {
user: 'data:image/svg+xml;base64,' + btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M16,4a5,5,0,1,1-5,5,5,5,0,0,1,5-5m0-2a7,7,0,1,0,7,7A7,7,0,0,0,16,2Z"/><path d="M26,30H24V25a5,5,0,0,0-5-5H13a5,5,0,0,0-5,5v5H6V25a7,7,0,0,1,7-7h6a7,7,0,0,1,7,7Z"/></svg>'),
globe: 'data:image/svg+xml;base64,' + btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M16,2A14,14,0,1,0,30,16,14.0158,14.0158,0,0,0,16,2Zm12,13H23.9131a22.9,22.9,0,0,0-2.2-8.7168A12.0732,12.0732,0,0,1,28,15Z"/></svg>')
};
instance.updateCustomHeaderItems([
{
id: 'language-selector',
text: 'English',
type: 'dropdown',
icon: ICONS.globe,
items: [
{
id: 'lang-en',
text: 'English',
onClick: () => instance.updateLocale('en')
},
{
id: 'lang-es',
text: 'Español',
onClick: () => instance.updateLocale('es')
}
]
},
{
id: 'help-button',
text: 'Help',
type: 'menu-item',
align: 'right',
icon: ICONS.user,
onClick: () => window.open('https://example.com/help', '_blank')
}
]);
// Customize home screen with personalized content
instance.updateWelcomeScreen({
welcomeMessage: 'Hello! How can I assist you today?',
description: 'Choose a topic below or type your question',
showTimestamp: true,
starterPrompts: [
{
id: 'prompt-1',
title: 'Get Started',
subtitle: 'Learn the basics',
prompt: 'How do I get started?'
},
{
id: 'prompt-2',
title: 'Documentation',
subtitle: 'Browse guides',
prompt: 'Show me the documentation'
}
]
});
});
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);
instance.on('view:pre:change', viewPreChange);
instance.on('view:change', viewChange);
}
window.wxOConfiguration = {
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>

