Chat Web SDK Sample Code
This page provides sample code to showcase core functionality, like exchanging messages or sending typing events. The samples are taken from the sample chat app .
Chat Messaging Functionality
Get or Create Thread Instances
const thread = await sdk.getThread('thread-id');
// Optionally recover a thread state (messages) from the server
const threadRecoveredData = await thread.recover();
Send Messages
thread.sendTextMessage('Message text');
Listen for New Messages
thread.onThreadEvent(ChatEvent.MESSAGE_CREATED, (event: CustomEvent<ChatEventData>) => {
// Do something with the event
event.detail.data.message;
});
Load More Messages
const loadMoreMessageResponse = await thread.loadMoreMessages();
Start and End Chats for LiveChat
To start and end a chat with a LiveChat channel, call the startChat() and endChat() methods.
await thread.startChat();
Custom Chat Features
Assign Messages to Agents
sdk.onChatEvent(ChatEvent.ASSIGNED_AGENT_CHANGED, (event: CustomEvent<ChatEventData>) => {
const agentName = parseAgentName((event.detail.data as AssignedAgentChangedData).inboxAssignee);
});
Handle Attachments
await thread.sendAttachments(fileList);
Send Typing Events
The following can be called multiple times, for example, on every keypress.
thread.keystroke();
// Optionally call stopTyping() when the user stops typing or leaves
thread.stopTyping();
Receive Typing Events
// Listen for START and STOP typing events
thread.onThreadEvent(ChatEvent.AGENT_TYPING_STARTED, (event: CustomEvent<ChatEventData>) => {
// Do something with the event
});
thread.onThreadEvent(ChatEvent.AGENT_TYPING_STOPPED, (event: CustomEvent<ChatEventData>) => {
// Do something with the event
});
Mark Messages as Read
await thread.lastMessageSeen();
Get Position in Queue for LiveChat
sdk.onChatEvent(ChatEvent.SET_POSITION_IN_QUEUE, (event) => {
if (isSetPositionInQueuePayload(event.detail)) {
setQueuePosition(event.detail.data.positionInQueue);
}
});
Multi-thread Actions
Get List of Threads
const threads = await sdk.getThreadList();
Load Metadata
const metadata = await thread.getMetadata();
Archive Thread
await thread.archive();
Set Thread Name
await thread.setName('New thread name');