Events
Your website can react to chat behavior by listening to events.
Contents
Overview
Events list
Event callbacks
View change reasons
Message object extensions
Event details
Migrating from window to view events and methods
Overview
The web chat uses an event system to communicate with your website. You can build your own custom UI responses, send messages to your assistant from your website code, or even have your website react to changes of state within the web chat.
To subscribe to events, use the on()
and once()
instance methods. Event handlers are called in the order in which they were registered.
Warning: The chat widget does not handle errors from your handlers. If your handler shows an error or rejects the returned Promise, the event processing stops and does not call event handlers. For example, if your code shows an error when it processes a pre:send event, the processing stops, and the message does not send.
Refer to the following example for 'receive'.
Example
// Register to listen for the "receive" event.
instance.on({ type: 'receive', handler: (event) => {
console.log('I received a message!', event);
});
Events list
The following table lists the events that web chat fires. For more information about events, see Event details.
Event | Fires When |
---|---|
Customization | |
customPanel:pre:close | Fires when the closing custom panel animation starts. |
customPanel:pre:open | Fires when the opening custom panel animation starts. |
customPanel:close | Fires when the animation for closing the custom panel ends. |
customPanel:open | Fires when the animation for opening the custom panel ends. |
customResponse Deprecated | Fires when a response receives an unrecognized or user_defined response type. This event has a new name. For more information, see userDefinedResponse. |
userDefinedResponse | Fires when a response receives an unrecognized or user_defined response type. |
Human agent | |
agent:areAnyAgentsOnline | This event fires after web chat calls "areAnyAgentsOnline" for a service desk. It occurs right after web chat receives a "connect_to_agent" response from the assistant. It reports the value that is returned from that call. It is useful if you want custom code to act if no agents are online. |
agent:endChat | This event fires after a chat with an agent ends. It fires after "agent:pre:endChat" but can fire when the user leaves the chat or the agent ends the chat. |
agent:pre:receive | This event fires before the system or human agent send a message. |
agent:pre:send | This event fires before the human agent sends a message. |
agent:pre:sessionHistory | This event fires before a message between the user and a live agent to the session history is added. Use it to modify the message, such as removing personal or sensitive data from storage by the assistant. |
agent:pre:startChat | This event fires before a chat starts with a service desk. It occurs when the user clicks the "Request agent" button before an attempt to communicate with the service desk. |
agent:pre:endChat | This event fires before a chat with an agent ends. It occurs after the user confirms ending the chat but can also fire if the agent ends the chat. |
agent:receive | This event fires after a message from a human agent or the system is received. |
agent:send | This event fires after a message to a human agent is sent. |
Messages | |
history:begin | Fires at the beginning of the web chat and reloads when you enable the session history and the session does not expire. |
history:end | Fires at the end of the web chat and reloads when you enable the session history and the session does not expire. |
pre:restartConversation | Fires when a request to restart the conversation and before any action is taken. |
pre:receive | Fires before the web chat receives a response from your assistant before the receive event. |
pre:send | Fires before the web chat sends a message to your assistant before the send event. |
receive | Fires when the web chat receives a response from your assistant after the pre:receive event. |
restartConversation | Fires after the conversation restarts and before a new conversation begins. |
send | Fires when the web chat sends a message to your assistant after the pre:send event. |
stopStreaming Beta | Fires when the user clicks on the "Stop response" button during a streamed response. |
Miscellaneous | |
chat:ready | Fires after web chat opens and is ready to receive input from the user. |
closePanelButton:toggled Deprecated | Fires after the close panel button is clicked. |
Security and identity | |
identityTokenExpired | Fires when security is enabled and your JWT token expires. |
Tours | |
tour:end Beta | Fires when the tour ends by clicking the done button at the end of the tour. |
tour:start Beta | Fires when a tour starts. |
tour:step Beta | Fires when the user sees a new step. |
View | |
view:change | Fires when the view state changes and after the view:pre:change event. |
view:pre:change | Fires before the view state changes and before the view:change event. |
window:close Deprecated | Fires when the chat window closes after the window:pre:close event. It is deprecated. For more information, see view:change. This event cannot work if you use the tours feature. |
window:pre:close Deprecated | Fires when the chat window closes before the window:close event. It is deprecated. For more information, see view:pre:change. This event cannot work if you use the tours feature. |
window:pre:open Deprecated | Fires when the chat window opens. This event fires before the web chat attempts to load any existing history data or before it requests the welcome message. It is deprecated. For more information, see view:pre:change. This event cannot work if you use the tours feature. |
window:open Deprecated | Fires when the chat window opens. It fires after web chat begins the process of loading existing history data and either requesting the welcome message or opening the home screen. It is deprecated. For more information, see view:change. This event cannot work if you use the tours feature. |
Event callbacks
When an event fires, web chat calls subscribed callbacks in the order in which they were subscribed by using the on
or once
method. Each callback receives two arguments:
- The event that fires.
- The current instance of web chat.
It is convenient because your handler has access to the instance without requiring you to store the value somewhere that is accessible to your handler. It is useful if you want to do something like send a message or open a custom panel as part of the logic of your handler.
To prevent accidental reassignment of data that other methods might use, the parameters for most callbacks are deep clones of the event data rather than references to the original objects. Various exceptions include the pre:send
and pre:receive
events. These events provide references to the original objects, making it possible for your code to manipulate the data before it passes to the send
or receive
events. For example, you use the pre:send
event to modify context variables before it sends a message to your assistant. Refer to the documentation for each event to determine which properties of the event are assignable or modifiable.
Asynchronous event callbacks
An event callback does not require a return value. However, you can optionally return a Promise object. If you return a Promise, processing of the event queue pauses until the Promise resolves. It can be useful for asynchronous methods that need to be called while preprocessing data from your pre:send
or pre:receive
event handlers.
Refer to the following example for asynchronous event callbacks.
Example
/**
* Waits 5 seconds before showing message.
*/
function handler(event) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('I waited 5 seconds before continuing!');
resolve();
}, 5000);
});
}
instance.on({ type: 'pre:receive', handler: handler });
View change reasons
This list is of the possible reasons when a view:pre:change or view:change event fires.
Reason | Description |
---|---|
calledChangeView | This event fires, when you call the changeView instance method. |
calledEndTour | This event fires, when you call the endTour instance method. |
calledRestartConversation | This event fires, when you call the restartConversation instance method. It fires only if the call results in a view change. |
calledStartTour | This event fires, when you call the startTour instance method. |
channelTransfer | This event fires, when web chat is first loaded as the result of a channel transfer. The main window automatically opens. |
launcherClicked | This event fires, when the users clicks the default launcher. It does not include custom launchers. |
linkID | This event fires, when web chat loads and the URL receives a link ID. The main window automatically opens. |
mainWindowClosedAndRestarted | This event fires, when the user clicks the "Close and restart" (X) button in the main window header. |
mainWindowMinimized | This event fires, when the user clicks the close/minimize (_) button in the main window header. |
sessionHistory | This event fires, when web chat first loads and finds an existing session, the view state for web chat sets to the same state it was previously in. |
tourCardRestartedTour | This event fires, when the user clicks the "Restart" button on a tour card to restart a tour. It opens the tour view and closes the main window. |
tourCardResumedTour | This event fires, when the user clicks the "Resume" button on a tour card to resume a tour. It opens the tour view and closes the main window. |
tourCardStartedTour | This event fires, when the user clicks the "Start" button on a tour card to start a tour. It opens the tour view and closes the main window. |
tourClosed | This event fires, when the user clicks the close (X) button from inside a tour. It closes the tour view and opens the launcher. |
tourDone | This event fires, when the user clicks the "Done" button from inside a tour when the tour is complete. It closes the tour view and opens the launcher. |
tourMinimized | This event fires, when the user clicks the minimize (_) button from inside a tour. It closes the tour view and opens the launcher. |
tourOpenedOtherView | This event fires, when the user clicks the "chat" button from inside a tour. It closes the tour view and opens the main window. |
tourSkipCard | This event fires, when a tour starts automatically after the user receives a tour card message from the assistant. It opens the tour view and closes the main window. |
webChatLoaded | This event fires, when web chat loads on a page in the default configuration and no other reasons occurr. It means that the launcher is open and the other views are closed but the openChatByDefault flag results in the opening of the main window. |
Message object extensions
web chat fires events to provide access to the message objects that either send to or receive from the assistant. For more information, see watsonx Assistant v2 message API documentation (either the Request
or Response
objects). In addition to the standard WA message format, web chat extends the message object with some additional data that is specific to web chat. The values all exist on a history
property on either the request or response object.
Note: Any properties that are not documented here are for internal use and not officially supported by custom code and can be changed at any time.
Refer to the following table and example for message object extensions.
Property | Type | Description |
---|---|---|
from_history | boolean |
This object indicates whether this message was retrieved from server session history when web chat was loaded. A value of false or an undefined property means that the message is new since web chat was loaded. |
is_welcome_request | boolean |
This object indicates whether this message is a request for the welcome node or a greeting. It occurs when web chat is first opened and with no existing session. The input text of the message is an empty string. |
label | string |
Some message requests include this property and represent the user-displayed text for the message, which is different than the message text that the assistant acts on. For message requests that generate as the result of the user that chooses a value from an option or suggestion response (buttons and dropdowns). The value in the input.text property of the request is the text sent to the assistant to act on. It is not the same as the user display text that corresponds to that value. This value is also what appears as the "user said" text that appears in the message list. |
silent | boolean |
This property can be included on either a message request or response and it indicates that this message is not displayed to the user. |
timestamp | Number |
The time a message was sent or received. This value on a request changes from the original value it had at the time that it was sent when the message is loaded from session history. The message originally uses the clock on the user's machine (which can be set incorrectly). When the message is loaded from session history, the value updates to use the time from the server when it received the request. |
user_defined | Object |
This object is present on messages that are loaded from session history that were updated with updateHistoryUserDefined . It enables to associate custom data with a previously sent or received message. For example, you can use it to track the data that the user entered in a field of a custom response so that if the user switches pages and web chat is reloaded, that data is still available to your custom response. |
Example
function preSendHandler(event) {
// Set a skill variable to the user's name if this message is a welcome request.
if (event.data.history.is_welcome_request) {
event.data.context.skills['actions skill'].skill_variables.User_Name = fullName;
}
}
Event details
agent:areAnyAgentsOnline
This event fires after web chat calls "areAnyAgentsOnline" for a service desk. It occurs right after web chat receives a "connect_to_agent" response from the assistant. It reports the value that is returned from that call. It is useful if you want custom code to act if no agents are online.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:areAnyAgentsOnline ) |
event.areAnyAgentsOnline | string |
This result is of the "areAnyAgentsOnline" call. A value of "online" indicates that agents are online. A value of "offline" indicates that agents are not online. A value of "unknown" indicates that the service desk did not report a result. It can occur if the service desk does not support this operation. If the service desk generated an error, then it returns an "offline" value. |
instance | Object |
The current instance of web chat |
agent:endChat
This event fires after a chat with an agent ends. It fires after agent:pre:endChat (except in cases where a request for an agent was cancelled) but can fire both from the user or the agent that end the chat. It can be useful for gathering post-chat information or conducting a survey with the user. A custom panel can be displayed to the user to collect this information.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:endChat ) |
event.endedByAgent | boolean |
Indicates whether the agent ends the chat instead of the user. |
event.requestCancelled | boolean |
Indicates whether the request for an agent was cancelled before one joined. It occurs when the user cancels the request or when an error occurs while trying to attempy to start a new chat. |
instance | Object |
The current instance of web chat |
agent:pre:startChat
This event fires before a chat with a service desk starts. It occurs when the user clicks the "Request agent" button and before any attempt is made to communicate with the service desk, which is useful to gather information before you connect to the service desk. A custom panel can be displayed to the user to collect this information. The service desk is not connected until all the event's handlers resolve. You can use this event to cancel the chat.
Refer to the following table and example for agent:pre:startChat
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (agent:pre:startChat ) |
|
event.message | Object |
The full v2 message API Response object that passes to the service desk. For more information, see API Reference. | |
event.cancelStartChat | boolean |
Yes | A listener can set this flag to indicate the cancellation of the chat process. |
event.sessionHistoryKey | String |
It is the session history key that loads an agent app version of web chat. This version of web chat can display the user's previous conversation to an agent. For more information, see Agent app. | |
event.preStartChatPayload | any |
Yes | A payload of data that passes to the service desk when a chat starts. The value that is assigned here passes to the service desk when its startChat function is called. The value that is expected here depends on the service desk integration that you are using. Refer to the integration's documentation for information on what is expected here or to see whether this property is supported. |
instance | Object |
The current instance of web chat |
Example
let preStartChatResolve;
let preStartChatEvent;
function preStartChatHandler(event, instance) {
// This Promise causes the "agent:pre:startChat" event to pause until the custom panel is closed.
// There is a click listener in the custom panel that resolves it.
return new Promise((resolve) => {
preStartChatResolve = resolve;
preStartChatEvent = event;
instance.customPanels.getPanel().open({ 'title': 'Connect to agent', hideCloseButton: true });
});
}
function createCustomPanel(panel) {
const container = document.createElement('div');
container.innerText = 'To get an agent, click this button:';
const button = document.createElement('button');
button.type = 'button';
button.innerText = 'Agent!';
button.addEventListener('click', () => {
// Once the user has clicked the button, close the panel, set a payload that can be made available to the service
// desk and the resolve the promise that our handler is waiting on to continue the connect to agent. What is passed
// here depends on the service desk (which cannot support this property).
preStartChatEvent.preStartChatPayload = { someData: 'Depends on the service desk' };
panel.close();
preStartChatResolve();
});
container.appendChild(button);
panel.hostElement.appendChild(container);
}
instance.on({ type: 'agent:pre:startChat', handler: preStartChatHandler });
createCustomPanel(instance.customPanels.getPanel());
agent:pre:sessionHistory
This event fires before a message between the user and a live agent is added to session history. It can modify the message to do things like remove the storage of personal or sensitive data by the assistant. This event fires only when the user or the service desk (a live agent) sends messages. It does not include messages from the web chat system such as "An agent joined the chat".
You can change the message to remove potential personal or sensitive data. You can also assign the entire message to null
, which prevents the storage of message. The messages fire with this event include bothRequest
and Response
messages. The exact contents of the response messages can vary depending on the use of service desk integration.
The session history reloads any stored messages if the user reloads web chat. If your custom code has access to sensitive information that is not available to the assistant, you can readd that information as part of the history:begin event.
This event does not fire if you disable agent session history by using the disableAgentSessionHistory option.
Refer to the following table and example for agent:pre:sessionHistory
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (agent:pre:sessionHistory ) |
|
event.message | Object |
Yes | The full v2 message API Request or Response object that a user or an agent sends. For more information, see API Reference. |
instance | Object |
The current instance of web chat |
Example
/**
* This handler processes messages between the user and an agent. It replaces any occurrences of the word
* "secret" (case insensitive) with "******" in session history. If a message contains the text "hide this message", the
* entire message is hidden from session history.
*/
async function agentPreSessionHistoryHandler(event) {
let hideWholeMessage = false;
if (event.message.output) {
// This is a message from an agent.
event.message.output.generic.forEach(item => {
// This code is only handling text messages. If the service desk can produce other types of message responses,
// (such as image responses), you need to add additional code for each of those possible types.
if (item.text) {
item.text = item.text.replace(/secret/gi, '******');
if (item.text.toLowerCase().includes('hide this message')) {
hideWholeMessage = true;
}
}
});
} else if (event.message.input) {
// This is a message from a user.
event.message.input.text = event.message.input.text.replace(/secret/gi, '******');
if (event.message.input.text.toLowerCase().includes('hide this message')) {
hideWholeMessage = true;
}
}
if (hideWholeMessage) {
event.message = null;
}
}
instance.on({ type: 'agent:pre:startSessionHistory', handler: agentPreSessionHistoryHandler });
agent:pre:endChat
This event fires before a chat with an agent is ended. It occurs after the user selects "Yes" from the confirmation modal but it can also fire if the agent ends the chat. It can be useful to gather post-chat information or conduct a survey with the user before disconnecting from the service desk. A custom panel displays to the user to collect this information. The web chat disconnects from the service desk after this event's handlers resolve. This event can also cancel ending the chat.
This event fires only if a chat successfully starts and an agent joins. If an error occurs while the chat starts or the request for an agent is cancelled before an agent joins, this event does not fire. It happens because ending the chat cannot be cancelled in these cases, which this event allows for. However, the event fires in specific situations. For more information, see agent:endChat.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (agent:pre:endChat ) |
|
event.endedByAgent | boolean |
Indicates whether the agent ends the chat instead of the user. | |
event.cancelEndChat | boolean |
Yes | Listeners set this flag to indicate that the end chat process cancels. |
event.preEndChatPayload | any |
Yes | Users pass some arbitrary payload of data to the service desk when they end a chat. The value that is assigned here passes to the service desk when its endChat function calls. |
instance | Object |
Represents the current instance of web chat. |
Example
For more information, see agent:pre:startChat to learn how to use the agent events to open a custom panel.
agent:pre:receive
This event fires before a message arrives from a human agent or the system.
Refer to the following table for agent:pre:receive
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:pre:receive ) |
event.data | Object |
Refers to a v2 message API request object. For more information, see API Reference. This parameter is a reference to the object that was received, so you can modify it in place. |
event.agentProfile | Object |
If the agent sends this message, it contains information about the agent. Messages from the system do not provide a value. |
event.agentProfile.id | string |
Represents a unique identifier for the agent. The value depends on the service desk in use. |
event.agentProfile.nickname | string |
The visible name for the agent. It can be the agent's full name or just a first name. |
event.agentProfile.profile_picture_url | string |
An optional URL pointing to a profile picture for the agent. |
instance | Object |
Represents the current instance of web chat. |
agent:pre:send
This event fires before a message goes to a human agent.
Refer to the following table for agent:pre:send
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:pre:send ) |
event.data | Object |
Refers to a v2 message API request object. For more information, see API Reference. This parameter is a reference to the object that is sent, so you can modify it in place. |
event.files | Array |
An array of files that the user requests to upload to the service desk. |
instance | Object |
Represents the current instance of web chat. |
agent:receive
This event fires after a message goes to a human agent or the system.
Refer to the following table for agent:receive
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:receive ) |
event.data | Object |
Refers to a v2 message API request object. For more information, see API Reference. |
event.agentProfile | Object |
If the agent sends this message, it contains information about the agent. Messages from the system do not provide a value. |
event.agentProfile.id | string |
A unique identifier for the agent. The value depends on the service desk in use. |
event.agentProfile.nickname | string |
The visible name for the agent. It can be the agent's full name or just a given name. |
event.agentProfile.profile_picture_url | string |
An optional URL pointing to a profile picture for the agent. |
instance | Object |
The current instance of web chat |
agent:send
This event fires after a message goes to a human agent.
Refer to the following table for agent:send
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:send ) |
event.data | Object |
Refers to a v2 message API request object. For more information, see API Reference. |
instance | Object |
The current instance of web chat |
Example
See the example for agent:pre:startChat to learn how to use the agent events to open a custom panel.
chat:ready
This event fires after web chat opens and gets ready to receive input from the user. It fires after both the window:pre:open and window:open events fire. This event also fires after web chat loads messages from session history (if an active session exists) or after the greeting message or home screen displays to the user. It marks when the message or the input fields of the home screen become visible and ready for input.
Refer to the following table for chat:ready
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (chat:ready ) |
instance | Object |
The current instance of web chat |
customPanel:close
This event fires when the closing animation of the custom panel ends.
Refer to the following table for customPanel:close
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:close ) |
instance | Object |
The current instance of web chat |
customPanel:open
This event fires when the opening animation of the custom panel ends.
Refer to the following table for customPanel:open
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:open ) |
instance | Object |
The current instance of web chat |
customPanel:pre:close
This event fires when the closing animation of the custom panel starts after the call, or when the user clicks the close button in the panel header. For more information, see panelInstance.close().
Refer to the following table for customPanel:pre:close
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:pre:close ) |
instance | Object |
The current instance of web chat |
customPanel:pre:open
This event fires when the opening animation of the custom panel starts after the call. For more information, see panelInstance.open().
Refer to the following table for customPanel:pre:open
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:pre:open ) |
instance | Object |
The current instance of web chat |
closePanelButton:toggled Deprecated
This event fires when the user clicks the "close panel" button. For more information, see closePanelButtonConfig. Refer to the following table.
It is deprecated. Use view:change instead.
Refer to the following table for closePanelButton:toggled
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (closePanelButton:toggled ) |
instance | Object |
The current instance of web chat |
sessionExpired
This event fires when a session is about to expire. It is an approximation based on a timer.
Refer to the following table for sessionExpired
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (sessionExpired ) |
event.session.id | String |
The session id that is about to expire |
instance | Object |
The current instance of web chat |
identityTokenExpired
This event fires when security is enabled and the JWT token needs refreshing.
Refer to the following table and example for identityTokenExpired
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (identityTokenExpired ) |
|
event.identityToken | String |
Yes | Sets a token in the same format as instance.updateIdentityToken(identityToken) and then retries the message. |
instance | Object |
The current instance of web chat |
Example
/**
* Update the identityToken.
*/
function handler(event) {
// Make your async call to fetch a new token here.
return makeCallToFetchApiToken().then(function (token) {
event.identityToken = token;
}
}
instance.on({ type: 'identityTokenExpired', handler: handler });
history:begin
Fires at the beginning of the web chat reloading when you enable session history. It indicates that the session does not expire and the messages from the session history re-render in the chat window. It supports editing messages, similar to pre:receive. The only events that fire between here and history:end is userDefinedResponse events (if a user_defined message appears in the history).
Refer to the following table and example for history:begin
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (history:begin ) |
event.messages | Array |
An array of the message requests and responses that occur during the session. Any updates that are saved for a message response with instance.updateHistoryUserDefined() is available within messages[n].history.user_defined. |
instance | Object |
The current instance of web chat |
Example
function receiveHandler(event) {
const { generic } = event.data.output;
for (let i = 0; i < generic.length; i++) {
const item = generic[i];
if (item.response_type === 'text') {
if (item.text === 'TypeScript isn't awesome :(' && !event.data.history.user_defined) {
// Since there's no history.user_defined info for this message it must be the first time we've seen it. (or at
// least the first time we're saving state for it).
// Lets save some state about the message response to be used on reload.
instance.updateHistoryUserDefined(
event.data.id,
{ state1: 'just kidding, TypeScript is awesome' }
);
}
}
}
}
instance.on({ type: 'receive', handler: receiveHandler });
function historyHandler(event){
for (let i = 0; i < event.messages.length; i++){
if(event.messages[i].history.user_defined?.state1 === 'just kidding, TypeScript is awesome'){
// On reload we found the state we saved for the message.
// Lets use the updated state instead of the original.
event.messages[i].output.generic[0].text = event.messages[i].history.user_defined.state1;
}
}
}
instance.on({ type: 'history:begin', handler: historyHandler });
history:end
Fires at the end of the web chat reloading when session history is enabled. This event indicates that the session does not expire and the messages from the session history rerender in the chat window. Messages are not allowed to be edited during this event.
Refer to the following table and example for history:end
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (history:end ) |
event.messages | Array |
An array of the message requests and responses that occur during the session. Any changes to messages in history:begin are visible here. |
instance | Object |
The current instance of web chat |
Example
function handler(event){
for (let i = 0; i < event.messages.length; i++){
// Console log the final versions of the messages after web chat reload.
console.log(event.message[i]);
}
}
instance.on({ type: 'history:end', handler: handler });
customResponse Deprecated
Fires when the web chat receives a response with an unrecognized response type from your assistant.
This event renames to maintain with the user_defined
response type that an assistant returns. Use userDefinedResponse instead. The existing event name continues to work but removes in a future version of web chat. The new event works the same and has the same properties, only the event's name changes.
userDefinedResponse
Fires when the web chat receives a user_defined response type or an unrecognized response type from your assistant. The event includes the response data and the DOM element where any response renders. Based on the response data, you can choose to render a custom view, perform an action on your website, or both.
There are two use cases for this event:
1. A user_defined
response type:
This response type enables to define your own content and provide your own code to render it. You can also mark a user_defined
response type as silent
and not render anything, but instead take some other action on your web page (for example, open a tutorial or interact with other widgets on the page). For more information, see examples of user_defined
response types.
2. A response type that web chat does not recognize:
This behavior allows userDefinedResponse handlers to restart when web chat reloads, which is necessary since there are new event.data.elements
to attach a userDefinedResponse to. If you need to save data for a userDefinedResponse so it can re-render with the same state in mind that it initially rendered, then use the instance.updateHistoryUserDefined() method. For more information, see tutorial.
Note: If you enable session history, then this event also fires in between the history:begin and history:end events.
Refer to the following table and examples for userDefinedResponse
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (userDefinedResponse ) |
|
event.data | Object |
Event data | |
event.data.message | Object |
The part of a v2 message API Response object that includes the response_type and user_defined fields. This parameter only includes the output.generic[n] part of the response that was received. | |
event.data.fullMessage | Object |
The full v2 message API Response object. For more information, see API Reference. This parameter is a copy of the response that was received and includes the message id needed to save userDefinedResponse state for session history. You can also access the context and history objects from this. | |
event.data.element | Element |
A DOM element inside the chat window where the response renders. It is null if a user_defined message has the silent attribute set to true . |
|
event.data.fullWidth | Boolean |
Yes | The event handler sets this value to indicate whether the message uses the full width of web chat. By default, the message displays padding on the left and right and aligns with the bot message indicator (the colored bar) or the avatar. |
instance | Object |
The current instance of web chat |
Example
function handler(event) {
const { message, fullMessage, element } = event.data;
// The "user_defined_type" property is just an example; it is not required. You can use any other property or
// condition you want here. It makes it easier to handle different response types if you have more than
// one custom response type.
if (event.data.message.user_defined?.user_defined_type === 'my_custom_response_type') {
// Grab the text from the message so we can put it into a button.
const text = message.text;
// Also grab the value of a context variable. If you are using an action skill, then replace
// "['main skill'].user_defined" with "['actions skill'].skill_variables".
const variable = fullMessage.context.skills['main skill'].user_defined.custom_var;
// Tell web chat to display the message as a full width message.
event.data.fullWidth = true;
// This defines the content of the custom response. You can put anything you want here. You can also use
// document.createElement and append children to the element if you want to create the elements in a more
// structured manner.
element.innerHTML = `<button type="button" class="MyCustomStyle">${text} ${variable}</div>`;
// It is just an example to show you how can look up an element from the HTML you just added above and add a
// listener to it.
const buttonElement = element.querySelector('.MyCustomStyle')
buttonElement.addEventListener('click', () => console.log('You clicked the button!'));
}
}
instance.on({ type: 'userDefinedResponse', handler: handler });
Example with session history
function handler(event, instance) {
const { element } = event.data;
// If there's no user_defined history then it must be the first time we've seen this custom response.
if (!event.data.fullMessage.history.user_defined) {
element.innerText = 'on reload this says "yay it worked"';
instance.updateHistoryUserDefined(
event.data.fullMessage.id,
{ firstSave: 'yay it worked' }
);
}
// If there is history and user_defined data then we must be seeing this userDefinedResponse after reload.
else if (event.data.fullMessage.history?.user_defined) {
if (event.data.fullMessage.history.user_defined.firstSave) {
element.innerText = event.data.fullMessage.history.user_defined.firstSave;
}
}
}
instance.on({ type: 'userDefinedResponse', handler: handler });
messageItemCustom
Fires by response types that support custom events.
Refer to the following table and example for messageItemCustom
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (messageItemCustom ) |
|
event.customEventType | String |
The specific type of this custom event. For more information, see Custom event types. | |
event.messageItem | Object |
The part of a v2 message API Response object that includes the response_type and user_defined fields. This parameter only includes the output.generic[n] part of the response that was received. | |
event.fullMessage | Object |
The full v2 message API Response object. For more information, see API Reference. This parameter is a copy of the response that was received and includes the message id needed to save userDefinedResponse state for session history. You can also access the context and history objects from this. | |
instance | Object |
The current instance of web chat |
Custom event types
A custom event type is based on the interaction with a response type that fires the messageItemCustom event.
Refer to the following table and example for custom event types.
Custom event type | Description |
---|---|
buttonItemClicked | Indicates the event fires when the user clicks a button from a button response type with a button_type of custom_event . |
Example
function handler(event) {
const { customEventType, messageItem, } = event;
// The 'custom_event_name' property comes from the button response type with button_type of custom_event.
if (customEventType === 'buttonItemClicked' && messageItem.custom_event_name === 'trigger_alert') {
alert('THIS IS AN ALERT!!!');
}
}
instance.on({ type: 'messageItemCustom', handler: handler });
pre:receive
Fires when receiving a response from the assistant, before the receive
event. The pre:receive
event allows you to synchronously manipulate the object that is referenced by event.data
before the web chat passes it to the receive
event for processing.
Refer to the following table and example for pre:receive
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (pre:receive ) |
event.data | Object |
A v2 message API response object. For more information, see API Reference. This parameter is a reference to the object that is received, so you can modify it in place. |
event.updateHistory | Boolean |
Defaults to True . If you enable session history, this flag allows you to automatically save updates that are made to messages in pre:receive. If the page reloads/changes after updates to a saved message, then the message rerenders the same way it was initially rendered (after the pre:receive edits). The updated message saves for the length of a session. |
instance | Object |
The current instance of web chat |
Example
/**
* Override our response_type for options with one of your own.
*/
function handler(event) {
const generic = event.data.output.generic;
for (let i = 0; i < generic.length; i++) {
const item = generic[i];
if (item.response_type === 'options') {
item.response_type = 'my_custom_options_override';
// Save changes made to this message so it rerenders the same way if session history is enabled.
event.updateHistory = true;
}
if (item.response_type === 'connect_to_agent') {
item.response_type = 'text';
item.text = 'All our agents are busy, please call us at 555-555-5555.'
// Don't save the changes made to this message, it rerenders the way web chat initially received it from the
// Assistant (even if session history is enabled).
event.updateHistory = false;
}
}
}
instance.on({ type: 'pre:receive', handler: handler });
pre:restartConversation
Fires when a request is made to restart the conversation. web chat does not execute any operations to restart the conversation. If you want the restart to cause web chat to close, call closeWindow(). If you use closeWindow()
, make sure to use await
or then
to ensure that the event waits for the close to complete before restarting.
Refer to the following table for pre:restartConversation
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (pre:restartConversation ) |
instance | Object |
The current instance of web chat |
pre:send
Fires when sending a message to the assistant, before the send
event. The pre:send
event allows you to synchronously manipulate the object referenced by event.data
before the web chat passes it to the send
event (for example, to update context data).
Note: If the total amount of time it takes to send a message and receive a response exceeds 40 seconds the message cancels and an error displays to the user. This includes the time that it takes to run all events as well as sending the message to the assistant.
Refer to the following table and example for pre:send
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (pre:send ) |
event.data | Object |
A v2 message API request object. For more information, see API Reference. This parameter is a reference to the object that sends, so you can modify it in place. |
instance | Object |
The current instance of web chat |
Example
/**
* Console out the context object.
*/
function handler(event) {
console.log(event.data.context); // You can also manipulate context here.
console.log(event.data.input); // You can also manipulate input here. Maybe filter private data?
}
instance.on({ type: 'pre:send', handler: handler });
receive
Fires when the web chat receives a response from your assistant, after the pre:receive
event. This event indicates that the response arrives; if the response type is recognized, the response renders in your chat window.
Refer to the following table and example for receive
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (receive ) |
event.data | Object |
A v2 message API response object. For more information, see API Reference. This parameter is a copy of the response that was received. |
instance | Object |
The current instance of web chat |
Example
/**
* Console.log out intents on every message you receive from your Assistant.
*/
function handler(event) {
console.log('intents:', event.data.output.intents);
}
instance.on({ type: 'receive', handler: handler });
restartConversation
Fires after the conversation restarts and before a new conversation begins. The previous conversation clears and the web chat state restarts to a default state. A new conversation does not begin yet. If you want the restart to trigger a custom welcome message, call send() with your custom message.
Refer to the following table for restartConversation
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (restartConversation ) |
instance | Object |
The current instance of web chat |
send
Fires when a user sends a message to the assistant, after the pre:send
event. This event indicates that the message sends to the assistant.
Refer to the following table and example for send.
Note: If the total time it takes to send a message and receive a response exceeds 40 seconds, the message cancels, and an error displays to the user. It includes the time that it takes to run all events and sends the message to the assistant.
Refer to the following table and example for send.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (send ) |
event.data | Object |
A v2 message API request object. For more information, see API Reference. This parameter is a copy of the message that was sent. |
instance | Object |
The current instance of web chat |
Example
function handler(event) {
console.log(event);
}
instance.on({ type: 'send', handler: handler });
stopStreamingBeta
Fires when the user clicks on the "Stop response" button during a streamed response. The "Stop response" button becomes visible when a streamed response is currently active in the chat and is cancellable.
Note: Even when the button is clicked, the button may still remain visible, but disabled, until the stream has stopped which may not always be immediate.
Example
function handler() {
// handle on stopStreaming
}
instance.on({ type: 'stopStreaming', handler: handler });
tour:end Beta
Fires when a user ends the tour by clicking the done button at the end of the tour. This event does not fire when the user clicks the close button on the tour or uses the endTour instance method.
Refer to the following table for tour:end
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (tour:end ) |
event.reason | string |
The reason the tour ended. For more information, see Tour end reasons. |
instance | Object |
The current instance of web chat |
Tour end reasons
This list is of the possible reasons that the tour ends and the value of the reason
property on the tour:end
event.
Refer to the following table for tour end reasons.
Reason | Description |
---|---|
done_clicked | Indicates the tour that is ended when the user clicks the done button at the end of the tour. |
tour:start Beta
This event fires when a tour starts. The tour starts when the web chat receives a tour message with skip_card: true
, when you use the instance method startTour, or when the user clicks the start tour card. This event does not fire when the user clicks the restart button.
Refer to the following table for tour:start
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (tour:start ) |
event.reason | string |
The reason the tour starts. For more information, see Tour start reasons. |
instance | Object |
The current instance of web chat |
Tour start reasons
This list is of the possible reasons that the tour starts and the value of the reason
property on the tour:start
event.
Refer to the following table for tour start reasons.
Reason | Description |
---|---|
start_tour_method | Indicates the tour starts by a call to the startTour instance method. |
skip_card | Indicates the tour starts because the skip_card property is set to true within the received tour JSON. |
start_tour_clicked | Indicates the tour starts because the user clicks the tour card's start button. |
tour:step Beta
This event fires when a new step shows to the user. This can happen when a tour starts/restarts, the user clicks the next or previous buttons within the tour, or when the instance methods goToNextStep or goToStep are used. This event does not fire when a tour resumes. This event contains all of the data for the step.
Refer to the following table for tour:step
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (tour:step ) |
event.step | object |
All of the data for the step saved in the step array JSON. It includes the response_type, the content of the response, and a step_id if you provide it. |
instance | Object |
The current instance of web chat |
view:change
This event fires when the view state changes and after the view:pre:change
event. This event represents a change in the state of one of the views within web chat. For example, this fires when the user clicks the launcher to close the launcher and open the main window. Or it fires if the user starts a tour where the tour view opens and the main window closes.
When web chat loads on a page, all views are closed, and a view:change
event fires that reflects the change from this state to the default state for a loaded web chat. This default state depends on various factors, including whether there is an active session or if openChatByDefault
is used.
If you implement a custom launcher or use a custom element, you listen for this event to change the visibility of the custom element or the launcher.
This event fires after the view becomes visible, but it allows you to cancel (reverse) the change or alter what views are visible after the event is complete.
When the main window opens for the first time, this event fires. It fires before web chat loads the previous conversation data (if any) or before it requests the welcome message. This allows you to open a custom panel if you want to display a pre-chat form the user has to fill out before interacting with your assistant.
The handler for this event can return a Promise. If it does, web chat waits for this Promise to resolve before considering the view change complete. This is when you perform actions, like displaying a pre-chat form. The Promise resolves after the user completes the form.
If you want to cancel or alter the change, you change either the cancelViewChange
or newViewState
properties on the event.
You can review our complete tutorial on how to implement pre- or post-chat forms using these events. The same logic applies to the view events as it does to the now deprecated window events.
Refer to the following table and example for view:change
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (view:change ) |
|
event.reason | string |
The reason the view changes. For more information, see View change reasons. | |
event.cancelViewChange | boolean |
Yes | If true, this indicates that the change cancels. Since the new view state already applies when this event fires, this property causes the view state to revert to its previous state. The view change events do not fire when it occurs. |
event.newViewState | Object |
Yes | The state that the view changes to. The values in this object can change if you want to alter the final view state that web chat uses. For more information, see changeView. |
event.oldViewState | Object |
The view state that exists before the change view operation begins. For more information, see changeView. | |
instance | Object |
The current instance of web chat |
Example
function handler(event) {
// Display a pre-chat form if the main window was opened because the launcher was clicked.
if (event.reason === 'defaultLauncherClicked' && event.newViewState.mainWindow) {
return new Promise((resolve, reject) => {
// Use a custom panel to display a pre-chat form. When the user completes the form, call the "resolve" function.
// ...
});
}
// Force the launcher to always stay open.
event.newView.launcher = true;
}
instance.on({ type: 'view:change', handler: handler });
view:pre:change
This event fires before the view state changes and before the view:change
event. This event represents a change in the state of one of the views within web chat. For example, this fires when the user clicks the launcher to close the launcher and open the main window. Or it fires if the user starts a tour where the tour view opens and the main window closes.
When web chat loads on a page, all views consider closed and a view:pre:change
event fires that reflects the change from this state to the default state for a loaded web chat. This default state depends on various factors including whether there is an active session or if openChatByDefault
applies.
When the main window opens for the first time, this event fires and it fires before web chat loads the previous conversation data (if any) or before it requests the welcome message. It allows you to send a different message first instead of requesting the welcome message to show a different first message to the user.
The handler for this event can return a Promise. If it does, web chat waits for this Promise to resolve before considering the view change to be complete.
If you want to cancel or alter the change, you can change either the cancelViewChange
or newViewState
properties on the event.
Refer to the following table and example for view:pre:change
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (view:pre:change ) |
|
event.reason | string |
The reason the view changes. For more information, see View change reasons. | |
event.cancelViewChange | boolean |
Yes | If true, this indicates that the change cancels. Since the new view state already applies when this event fires, this property causes the view state to revert to its previous state. The view change events do not fire when it occurs. |
event.newViewState | Object |
Yes | The state that the view changes to. The values in this object can change if you want to alter the final view state that web chat uses. For more information, see changeView. |
event.oldViewState | Object |
The view state that exists before the change view operation begins. For more information, see changeView. | |
instance | Object |
The current instance of web chat |
Example
function handler(event, instance) {
// Trigger a different welcome message to be displayed to the user when the main window is opened from the launcher.
if (event.reason === 'defaultLauncherClicked' && event.newViewState.mainWindow) {
instance.send('Show me credit cards', { silent: true });
}
// Force the launcher to always stay open.
event.newView.launcher = true;
}
instance.on({ type: 'view:pre:change', handler: handler });
window:close Deprecated
This event fires when the web chat window closes, after the window:pre:close
event.
It is deprecated. Use view:change instead. This event cannot work as expected if you use the tours feature.
Refer to the following table for window:close
.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (window:close ) |
instance | Object |
The current instance of web chat |
window:pre:close Deprecated
This event fires when the web chat window closes, before the window:close
event. Return a Promise here ti prevent the web chat window from closing until the promise resolves.
It is deprecated. Use view:pre:change instead. This event cannot work as expected if you are using the tours feature.
Refer to the following table and example for window:pre:close
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:pre:close ) |
|
event.cancelClose | boolean |
Yes | If true, indicates canceling the close action. |
instance | Object |
The current instance of web chat |
Example
/**
* Stop the window from closing by setting cancelClose in the event handler.
*/
function handler(event) {
return new Promise(function(resolve, reject) {
event.cancelClose = true;
resolve();
});
}
instance.on({ type: 'window:pre:close', handler: handler });
window:pre:open Deprecated
This event fires when the chat window opens. This event fires before the web chat attempts to load any existing history data or before it requests the welcome message. Use it to send a different message first if you want to customize the welcome message that displays.
It is deprecated. Use view:pre:change instead. This event cannot work as expected if you are using the tours feature.
Refer to the following table for window:pre:open
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:pre:open ) |
|
event.reason | string |
The reason the window opens. For more information, see Window open reasons. | |
event.cancelOpen | boolean |
Yes | If true, indicates that the open cancels and the window does not open. |
instance | Object |
The current instance of web chat |
window:open Deprecated
This event fires when the chat window opens and fires before the web chat attempts to load any existing history data or before it requests the welcome message. Use it to send a different message first if you want to customize the welcome message that displays. You can also use this event to open a custom panel that can display a pre-chat form for gathering data from the customer before starting the conversation.
It is deprecated. Use view:change instead. This event cannot work as expected if you are using the tours feature.
Refer to the following table for window:open
.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:open ) |
|
event.reason | string |
The reason the window opens. For more information, see Window open reasons. | |
event.cancelOpen | boolean |
Yes | If true, indicates the open cancels. Since the window is already open when this event fires, the property causes the window to close. The window close events do not fire when it occurs. |
instance | Object |
The current instance of web chat |
Window open reasons
This list is of the possible reasons that the web chat window opens and the value of the reason
property on the window:open
and window:pre:open
events.
Refer to the following table for Window open reasons
.
Reason | Description |
---|---|
called_open_window | Indicates widget opens by a call to the instance function openWindow or toggleOpen . |
default_launcher | Indicates the user clicks the built-in launcher button that opebs the web chat. |
link | Indicates the widget opens because a link ID finds that starts a specific conversation. For more information, see Creating links to web chat. |
open_by_default | Indicates the widget opens because the openChatByDefault property sets to true. |
session_history | Indicates the widget opens as a result of session history. |
Wildcard (*)
Wildcard event. When an event fires, callbacks that subscribe to the wildcard event call after any subscriptions to the specific event type.
Refer to the following table and example for wildcard.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (* ) |
event.data | Object |
Event data (content depends on event type) |
instance | Object |
The current instance of web chat |
Example
function handler(event) {
console.log(event.type);
}
instance.on({ type: '*', handler: handler });
Migrating from window to view events and methods
In web chat 7.5.0, additional support for the tours feature becomes available. Tours adds a new "view" to web chat to the existing launcher and main window "views". With three views instead of two, the previous methods and events for opening and closing the main window create ambiguouity during tours. To address this, the window-related methods and events are deprecated in favor of a more generic "view change" system that explicitly supports tours.
The current window methods and events still support existing web chats and assistants but are deprecated and remove in a future version of web chat. This section helps explain how to migrate from the window methods and events to the view change ones.
Note: The window methods and events support existing assistants. If you add tours to your assistant, your window events and methods no longer work as expected. As such, the window methods and events do not support if you also use tours. If you decide to add tours to your assistant, update any of your custom code to use the new view change methods and events.
Migrating methods
The openWindow, closeWindow, and toggleOpen methods are deprecated. The changeView method is the replacement.
To change any usage of openWindow
or closeWindow
, change the code to call changeView
and pass either 'mainWindow'
or 'launcher'
as the new view.
// Old code.
instance.openWindow();
// New code.
instance.changeView('mainWindow');
// Old code.
instance.closeWindow();
// New code.
instance.changeView('launcher');
To migrate from the toggleOpen
method, examine the current view state of the main window to determine whether it opens or closes.
// Old code.
instance.toggleOpen();
// New code.
instance.changeView(instance.getState().viewState.mainWindow ? 'launcher' : 'mainWindow');
Migrating events
The window:pre:open, window:open, window:pre:close, and window:close events are now deprecated. The view:pre:change and view:change events are the replacements.
If you rely on the reason
property in the window events, For more information, see view change reasons since they differ and make sure that your code executes for the right reasons.
// Old code.
function handleWindowOpen(event) {
// Do something when the window opens.
}
instance.on({ type: 'window:open', handler: handleWindowOpen });
// New code.
function handleViewChange(event) {
if (event.newViewState.mainWindow) {
// Do something when the window opens.
}
}
instance.on({ type: 'view:change', handler: handleViewChange });