Events
Your website can react to web 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. By using these events, 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 provide any special handling of errors that are thrown from your handlers. If your handler throws an error or rejects the returned Promise, processing of the event that triggered the event stops, and no additional event handlers are called. For example, if your code throws an error while processing a pre:send event (which web chat fires before sending a message), processing stops and the message is not sent.
Example
<script>
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
onLoad: async (instance) => {
// Register to listen for the "receive" event.
instance.on({ type: 'receive', handler: (event) => {
console.log('I received a message!', event);
});
// Render the web chat.
await instance.render();
}
};
setTimeout(function(){const t=document.createElement('script');t.src='https://web-chat.global.assistant.watson.appdomain.cloud/versions/' + (window.watsonAssistantChatOptions.clientVersion || 'latest') + '/WatsonAssistantChatEntry.js';document.head.appendChild(t);});
</script>
Events list
The following table lists the events that are fired by web chat. For more information about an event, see Event details.
Event | Fired When |
---|---|
Customization | |
customPanel:pre:close | Fired when the custom panel closing animation has started. |
customPanel:pre:open | Fired when the custom panel opening animation has started. |
customPanel:close | Fired when the custom panel closing animation has ended. |
customPanel:open | Fired when the custom panel opening animation has ended. |
customResponse | Fired if a response with an unrecognized or user_defined response type is received. |
messageItemCustom | Fired by a watsonx Assistant response types that support custom events. |
Human agent | |
agent:areAnyAgentsOnline | This event is fired after web chat calls "areAnyAgentsOnline" for a service desk. This occurs right after web chat receives a "connect_to_agent" response from the assistant. It will report the value returned from that call. This is particularly useful if you want custom code to take action if no agents are online. |
agent:endChat | This event is fired after a chat with an agent has ended. This is fired after "agent:pre:endChat" but can be fired both from the user leaving the chat or the agent ending the chat. |
agent:pre:receive | This event is fired before a message is received either from a human agent or from the system. |
agent:pre:send | This event is fired before a message is sent to a human agent. |
agent:pre:sessionHistory | This event is fired before a message between the user and a live agent is added to session history. It can be used to modify the message in order to do things like remove personal or sensitive data from being stored by IBM watsonx Assistant. |
agent:pre:startChat | This event is fired before a chat with a service desk has started. This occurs as soon as the user clicks the "Request agent" button and before any attempt is made to communicate with the service desk. |
agent:pre:endChat | This event is fired before a chat with an agent is ended. This occurs after the user has confirmed they want to end the chat but it can also be fired if the chat is ended by the agent. |
agent:receive | This event is fired after a message is received either from a human agent or from the system. |
agent:send | This event is fired after a message is sent to a human agent. |
Messages | |
history:begin | Fired at the beginning of the web chat reloading when session history is enabled and the session hasn't expired. |
history:end | Fired at the end of the web chat reloading when session history is enabled and the session hasn't expired. |
pre:restartConversation | Fired when a request is made to restart the conversation and before any action is taken. |
pre:send | Fired before the web chat sends a message to your assistant, before the send event. |
receive | Fired when the web chat receives a response from your assistant, after the pre:receive event. |
restartConversation | Fired after the conversation is restart and before a new conversation has begun. |
send | Fired when the web chat sends a message to your assistant, after the pre:send event. |
Miscellaneous | |
chat:ready | Fired after web chat has opened and is ready to receive input from the user. |
* | Fired with every event. |
Security and identity | |
identityTokenExpired | Fired when security is enabled and your JWT token has expired. |
Tours | |
tour:end Beta | Fired when the tour is ended by clicking the done button at the end of the tour. |
tour:start Beta | Fired when a tour is started. |
tour:step Beta | Fired when a new step is shown to the user. |
View | |
view:change | Fired when the view state has changed and after the view:pre:change event. |
view:pre:change | Fired before the view state has changed and before the view:change event. |
window:close Deprecated | Fired when the chat window is closed, after the window:pre:close event. This is deprecated. Use view:change instead. Also note that this event may not work as expected if you are using the tours feature. |
window:pre:close Deprecated | Fired when the chat window is closed, before the window:close event. This is deprecated. Use view:pre:change instead. Also note that this event may not work as expected if you are using the tours feature. |
window:pre:open Deprecated | Fired when the chat window is opened. This event is fired before the web chat attempts to load any existing history data or before it requests the welcome message. This is deprecated. Use view:pre:change instead. Also note that this event may not work as expected if you are using the tours feature. |
window:open Deprecated | Fired when the chat window is opened. This is fired after web chat begins the process of loading existing history data and either requesting the welcome message or opening the home screen. This is deprecated. Use view:change instead. Also note that this event may not work as expected if you are using the tours feature. |
Event callbacks
When an event fires, subscribed callbacks are called in the order in which they were subscribed using the on
or once
method. Each callback is passed two arguments. The first argument is the event that is being fired. The second argument is the current instance of web chat. This is a convenience so your handler has access to the instance without you having to store the value somewhere that is accessible to your handler. This may be 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 might be in use by other methods, the parameters for most callbacks are deep clones of the event data rather than references to the original objects. There are a number of exceptions such as the pre:send
and pre:receive
events. These events do provide references to the original objects, making it possible for your code to manipulate the data before it is passed on to the send
or receive
events. For example, you might use the pre:send
event to modify context variables before sending a message to your assistant. Refer to the documentation for each event to determine which properties of the event are assignable or modifiable.
Asyncronyous 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 is resolved. This can be useful for asynchronous methods that need to be called while preprocessing data from your pre:send
or pre:receive
event handlers.
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 is a list of the possible reasons that may be provided when a view:pre:change or view:change event is fired.
Reason | Description |
---|---|
calledChangeView | When the changeView instance method is called. |
calledEndTour | When the endTour instance method is called. |
calledRestartConversation | When the restartConversation instance method is called. This event is only fired if the call actually results in a view change occurring. |
calledStartTour | When the startTour instance method is called. |
channelTransfer | When web chat is first loaded as the result of a channel transfer. The main window is automatically opened. |
launcherClicked | When the default launcher is clicked. This reason does not include custom launchers. |
linkID | When web chat is loaded and a link ID is provided in the URL. The main window is automatically opened. |
mainWindowClosedAndRestarted | When the user clicks the "Close and restart" (X) button in the main window header. |
mainWindowMinimized | When the user clicks the close/minimize (_) button in the main window header. |
sessionHistory | When web chat is first loaded and an existing session was found. The view state for web chat will be set to the same state it was in previously. |
tourCardRestartedTour | When the user clicks the "Restart" button on a tour card to restart a tour. This will open the tour view and close the main window. |
tourCardResumedTour | When the user clicks the "Resume" button on a tour card to resume a tour. This will open the tour view and close the main window. |
tourCardStartedTour | When the user clicks the "Start" button on a tour card to start a tour. This will open the tour view and close the main window. |
tourClosed | When the user clicks the close (X) button from inside a tour. This will close the tour view and open the launcher. |
tourDone | When the user clicks the "Done" button from inside a tour when the tour is complete. This will close the tour view and open the launcher. |
tourMinimized | When the user clicks the minimize (_) button from inside a tour. This will close the tour view and open the launcher. |
tourOpenedOtherView | When the user clicks the "chat" button from inside a tour. This will close the tour view and open the main window. |
tourSkipCard | When a tour starts automatically after the user has received a tour card message from the assistant. This will open the tour view and close the main window. |
webChatLoaded | When web chat is loaded on a page in the default configuration and when no other reasons have occurred. This usually means that the launcher is open and the other views are closed but the openChatByDefault flag will result in the main window being open instead. |
Message object extensions
Many of the events fired by web chat provide access to the message objects that are either sent to or received from IBM watsonx Assistant. The format of these messages is documented in the IBM 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.
The available properties are documented below. Any properties not documented here are for internal use and not officially supported by custom code and may be changed at any time.
Property | Type | Description |
---|---|---|
from_history | boolean |
Indicates if this message was retrieved from server session history when web chat was loaded. A value of false or an undefined property means the message is new since web chat was loaded. |
is_welcome_request | boolean |
Indicates if this message is a request for the welcome node or greeting. This occurs when web chat is first opened and there is not an existing session. The input text of the message will be an empty string. |
label | string |
This property is included on some message requests and represents the user displayed text for the message which might be different than the actual message text that the assistant acts on. For message requests that were generated as the result of the user choosing 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 for it to act on but this is not necessarily 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 should not be displayed to the user. |
timestamp | Number |
The time a message was sent or received. Note that this value on a request will change from the original value it had at the time it was sent when the message is loaded from session history. The message will originally use the clock on the end user's machine (which could be set incorrectly). When the message is loaded from session history, the value will be updated to use the time from the server when it received the request. |
user_defined | Object |
This object is present on messages loaded from session history that were updated with updateHistoryUserDefined . This allows you to associate custom data with a previously sent or received message. For example, you could use this to keep track of the data 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 is fired after web chat calls "areAnyAgentsOnline" for a service desk. This occurs right after web chat receives a "connect_to_agent" response from the assistant. It will report the value returned from that call. This is particularly useful if you want custom code to take action if no agents are online.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:areAnyAgentsOnline ) |
event.areAnyAgentsOnline | string |
This is the result 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. This may occur if the service desk does not support this operation. If the service desk generated an error, then "offline" will be returned. |
instance | Object |
The current instance of web chat |
agent:endChat
This event is fired after a chat with an agent has ended. This is fired after agent:pre:endChat (except in cases where a request for an agent was cancelled) but can be fired both from the user ending the chat or the agent ending the chat. This 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 if the chat was ended by the agent instead of the user. |
event.requestCancelled | boolean |
Indicates if the request for an agent was cancelled before one joined. This occurs when the user cancels the request or when an error occurs while attempting to start a new chat. |
instance | Object |
The current instance of web chat |
agent:pre:startChat
This event is fired before a chat with a service desk has started. This occurs as soon as the user clicks the "Request agent" button and before any attempt is made to communicate with the service desk. This can be useful for gathering information before connecting to the service desk. A custom panel can be displayed to the user to collect this information. The service desk is not connected to until after all this event's handlers have resolved.
This event can also be used to cancel the chat.
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 will be passed to the service desk. (For more information, see the API Reference) | |
event.cancelStartChat | boolean |
Yes | This flag can be set by a listener to indicate that the chat process should be cancelled. |
event.preStartChatPayload | any |
Yes | Some arbitrary payload of data that will be passed to the service desk when a chat is started. The value assigned here will be passed to the service desk when its startChat function is called. Note that the value 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 if this property is supported. |
instance | Object |
The current instance of web chat |
Example
let preStartChatResolve;
let preStartChatEvent;
function preStartChatHandler(event, instance) {
// This Promise will cause the "agent:pre:startChat" event to pause until the custom panel is closed.
// There is a click listener in the custom panel that will resolve 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 may not support this property).
preStartChatEvent.preStartChatPayload = { someData: 'Depends on the service desk' };
panel.close();
preStartChatResolve();
});
container.appendChild(button);
panel.hostElement.appendChild(container);
}
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
onLoad: async (instance) => {
await instance.render();
// Set up the custom panel and register a listener that will open it and wait for the button to be clicked.
instance.on({ type: 'agent:pre:startChat', handler: preStartChatHandler });
createCustomPanel(instance.customPanels.getPanel());
}
};
setTimeout(function(){
const t=document.createElement('script');
t.src='https://web-chat.global.assistant.watson.appdomain.cloud/versions/' + (window.watsonAssistantChatOptions.clientVersion || 'latest') + '/WatsonAssistantChatEntry.js';
document.head.appendChild(t);
});
agent:pre:sessionHistory
This event is fired before a message between the user and a live agent is added to session history. It can be used to modify the message in order to do things like remove personal or sensitive data from being stored by IBM watsonx Assistant. Note that only messages sent by the user or messages sent by the service desk (i.e. a live agent) are fired with this event; web chat system messages like "An agent joined the chat" are not included.
You can make any changes required to the message to remove potential personal or sensitive data. You can also assign the entire message to null
which will prevent the message from being stored at all. The messages fired with this event include bothRequest
and Response
messages. The exact contents of the response messages may vary depending on the service desk integration being used.
Any messages stored in session history will be reloaded if the user reloads web chat. If your custom code has access to sensitive information that is not available to IBM watsonx Assistant, you can re-add that information as part of the history:begin event.
Note that this event is not fired if agent session history has been disabled using the disableAgentSessionHistory option.
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 was sent by a user or an agent. (For more information, see the API Reference) |
instance | Object |
The current instance of web chat |
Example
/**
* This handler will process messages between the user and an agent. It will replace any occurrences of the word
* "secret" (case insensitive) with "******" in session history. If a message contains the text "hide this message", the
* entire message will be 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 may 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;
}
}
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
onLoad: async (instance) => {
await instance.render();
instance.on({ type: 'agent:pre:startSessionHistory', handler: agentPreSessionHistoryHandler });
}
};
setTimeout(function(){
const t=document.createElement('script');
t.src='https://web-chat.global.assistant.watson.appdomain.cloud/versions/' + (window.watsonAssistantChatOptions.clientVersion || 'latest') + '/WatsonAssistantChatEntry.js';
document.head.appendChild(t);
});
agent:pre:endChat
This event is fired before a chat with an agent is ended. This occurs after the user has selected "Yes" from the confirmation modal but it can also be fired if the chat is ended by the agent. This can be useful for gathering post-chat information or conducting a survey with the user before disconnecting from the service desk. A custom panel can be displayed to the user to collect this information. The service desk is not disconnected from until after all this event's handlers have resolved.
This event can also be used to cancel ending the chat.
Note that this event is only fired if a chat was successfully started and an agent joined. If an error occurs while starting the chat or the request for an agent is cancelled before an agent joins, this event is not fired (since ending the chat cannot be cancelled in these cases which this event allows for). However, the agent:endChat event is fired in these cases.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (agent:pre:endChat ) |
|
event.endedByAgent | boolean |
Indicates if the chat was ended by the agent instead of the user. | |
event.cancelEndChat | boolean |
Yes | This flag can be set by a listener to indicate that the end chat process should be cancelled. |
event.preEndChatPayload | any |
Yes | Some arbitrary payload of data that will be passed to the service desk when a chat is ended. The value assigned here will be passed to the service desk when its endChat function is called. |
instance | Object |
The current instance of web chat |
Example
See the example for agent:pre:startChat for how to use the agent events to open a custom panel.
agent:pre:receive
This event is fired before a message is received either from a human agent or from the system.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:pre:receive ) |
event.data | Object |
A v2 message API request object. (For more information, see the API Reference) Note that this parameter is a reference to the object that was received, so you can modify it in place. |
event.agentProfile | Object |
If this message was sent by an agent, this may contain information about the agent. Messages sent by the system will not provide a value for this. |
event.agentProfile.id | string |
A unique identifier for the agent. The value assigned here depends on the service desk being used. |
event.agentProfile.nickname | string |
The visible name for the agent. This 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 |
The current instance of web chat |
agent:pre:send
This event is fired before a message is sent to a human agent.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:pre:send ) |
event.data | Object |
A v2 message API request object. (For more information, see the API Reference) Note that this parameter is a reference to the object that will be sent, so you can modify it in place. |
event.files | Array |
An array of files that the user has requested to upload to the service desk. |
instance | Object |
The current instance of web chat |
agent:receive
This event is fired after a message is received either from a human agent or from the system.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:receive ) |
event.data | Object |
A v2 message API request object. (For more information, see the API Reference) |
event.agentProfile | Object |
If this message was sent by an agent, this may contain information about the agent. Messages sent by the system will not provide a value for this. |
event.agentProfile.id | string |
A unique identifier for the agent. The value assigned here depends on the service desk being used. |
event.agentProfile.nickname | string |
The visible name for the agent. This 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 |
The current instance of web chat |
agent:send
This event is fired after a message is sent to a human agent.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (agent:send ) |
event.data | Object |
A v2 message API request object. (For more information, see the API Reference) |
instance | Object |
The current instance of web chat |
Example
See the example for agent:pre:startChat for how to use the agent events to open a custom panel.
chat:ready
Fired after web chat has opened and is ready to receive input from the user. This is fired after both the window:pre:open and window:open events have fired. It is also fired after web chat has loaded messages from session history (if there is a session currently active) or after the welcome or greeting message or the home screen has been displayed to the user. This is the point at which the message or home screen input fields become visible and ready for input.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (chat:ready ) |
instance | Object |
The current instance of web chat |
customPanel:close
Fired when the custom panel closing animations has ended.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:close ) |
instance | Object |
The current instance of web chat |
customPanel:open
Fired when the custom panel opening animation has ended.
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
Fired when the custom panel closing animation has started after calling panelInstance.close() or the user clicks the close button in the panel header.
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
Fired when the custom panel opening animation has started after calling panelInstance.open().
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (customPanel:pre:open ) |
instance | Object |
The current instance of web chat |
identityTokenExpired
Fired when security is enabled and the JWT token needs to be refreshed.
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
Fired at the beginning of the web chat reloading when session history is enabled. This event indicates that the session hasn't expired and the messages from the session history are going to be re-rendered in the chat window. Messages are allowed to be edited during this event (similar to pre:receive). The only events that will fire between here and history:end will be customResponse events (if a customResponse occurs in history).
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 have occurred during the session. Any updates saved for a message response with instance.updateHistoryUserDefined() will be 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
Fired at the end of the web chat reloading when session history is enabled. This event indicates that the session hasn't expired and the messages from the session history have been re-rendered in the chat window. Messages aren't allowed to be edited during this event.
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 have occurred during the session. Any changes made to messages in history:begin will be 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
Fired when the web chat receives a response with an unrecognized response type from your assistant. The event includes the response data and the DOM element where any response should be rendered. Based on the response type, you can choose to render a custom view, perform an action on your website, or both.
There are two use cases for this event.
-
A
user_defined
response type. This is a response type that enables you to define your own content and provide your own code to render it. You can also mark auser_defined
response type assilent
and not render anything, but instead take some other action on your web page (for example, opening a tutorial or interacting with other widgets on the page). For more information, see the examples ofuser_defined
response types. -
A response type that web chat does not recognize.
Note: if session history is enabled then this event will also fire in between the history:begin and history:end events. This is done so that customResponse handlers can be re-invoked when web chat reloads which is necessary since there will be new event.data.elements
to attach a customResponse to. If data needs to be saved for a customResponse so that it can be re-rendered with the same state in mind that it was initially rendered with then use the instance.updateHistoryUserDefined() method. For more info and examples take a look at this tutorial.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (customResponse ) |
|
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 the API Reference.) This parameter is a copy of the response that was received and includes the message id needed to save customResponse 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 should be rendered. This will be null if a user_defined message has the silent attribute set to true . |
|
event.data.fullWidth | Boolean |
Yes | The event listener can set this value to indicate if the message should be rendered using the full width of web chat. By default, messages will display padding on the left and right and the message will align 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. This 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>`;
// This 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: 'customResponse', handler: handler });
messageItemCustom
Fired by a watsonx Assistant response types that support custom events.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (messageItemCustom ) |
|
event.customEventType | String |
The specific type of this custom event. 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 the API Reference.) This parameter is a copy of the response that was received and includes the message id needed to save customResponse 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 watsonx Assistant response type that fired the messageItemCustom event. The chart below describes the different custom events types that can be triggered.
Custom event type | Description |
---|---|
buttonItemClicked | Indicates the event was fired when the user clicked a button from a button response type with a button_type of custom_event . |
Example
function customEventHandler(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 });
Example with session history
function handler(event, instance) {
const { element } = event.data;
// If there's no user_defined history then this must be the first time we've seen this custom response.
if (!event.data.fullMessage.history.user_defined) {
element.innerText = 'on reload this will say "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 customResponse 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: 'customResponse', handler: handler });
pre:receive
Fired when receiving a response from the assistant, before the receive
event. The pre:receive
event gives you the opportunity to synchronously manipulate the object referenced by event.data
before the web chat passes it to the receive
event for processing.
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 the API Reference.) Note that this parameter is a reference to the object that will be received, so you can modify it in place. |
event.updateHistory | Boolean |
Defaults to True . If session history is enabled this flag allows you to automatically save updates made to messages in pre:receive. If the page is reloaded/changed after updates to a message have been saved then the message will re-render the same way it was initially rendered (after the pre:receive edits). Note: the updated message will only be saved 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 will be re-rendered 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 will re-render 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
Fired when a request is made to restart the conversation. At this point web chat has not executed any operations to restart the conversation. If you want the restart to cause web chat to close this event would be a good place to call closeWindow(). If you do use closeWindow()
, make sure to use await
or then
to ensure the event will wait for the close to complete before doing the restart.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (pre:restartConversation ) |
instance | Object |
The current instance of web chat |
pre:send
Fired when sending a message to the assistant, before the send
event. The pre:send
event gives you the opportunity 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 will be canceled and an error will be displayed to the user. This includes the time it takes to run all events as well as sending the message to the assistant.
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 the API Reference) Note that this parameter is a reference to the object that will be sent, 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
Fired when the web chat receives a response from your assistant, after the pre:receive
event. This event indicates that the response has been received; if the response type is recognized, the response is then rendered in your chat window.
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 the 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
Fired after the conversation is restart and before a new conversation has begun. At this point the previous conversation has been cleared and the web chat state has been restart to a default state. However a new conversation has not yet begun. If you wish the restart to trigger a custom welcome message, this event would be a good place to call send()with your custom message.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (restartConversation ) |
instance | Object |
The current instance of web chat |
send
Fired when sending a message to the assistant, after the pre:send
event. This event indicates that the message has been sent to the assistant.
Note: If the total amount of time it takes to send a message and receive a response exceeds 40 seconds the message will be canceled and an error will be displayed to the user. This includes the time it takes to run all events as well as sending the message to the assistant.
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 the 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 });
tour:end Beta
Fired when the tour is ended by clicking the done button at the end of the tour. This event is not fired when the close button on the tour is clicked or the endTour instance method is used.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (tour:end ) |
event.reason | string |
The reason the tour ended. See Tour end reasons for an explanation of the possible values here. |
instance | Object |
The current instance of web chat |
Tour end reasons
This is a list of the possible reasons that the tour has ended and the value of the reason
property on the tour:end
event.
Reason | Description |
---|---|
done_clicked | Indicates the tour ended by the user clicking the done button at the end of the tour. |
tour:start Beta
Fired when a tour is started. The tour could be started upon receipt of a tour message with skip_card: true
, when the instance method startTour is used, or when the start tour card is clicked by the user. This event is not fired when the restart button is clicked.
Parameter | Type | Description |
---|---|---|
event | Object |
The event |
event.type | String |
Event type (tour:start ) |
event.reason | string |
The reason the tour started. See Tour start reasons for an explanation of the possible values here. |
instance | Object |
The current instance of web chat |
Tour start reasons
This is a list of the possible reasons that the tour has started and the value of the reason
property on the tour:start
event.
Reason | Description |
---|---|
start_tour_method | Indicates the tour started by a call to the startTour instance method. |
skip_card | Indicates the tour started because the skip_card property was set to true within the tour JSON that was received. |
start_tour_clicked | Indicates the tour started because the user clicked on the tour card's start button. |
tour:step Beta
Fired when a new step is shown to the user. This could be caused by a tour starting/restarting, the user clicking the next or previous buttons within the tour, or when the instance methods goToNextStep or goToStep are used. This event is not fired when a tour is resumed. This event contains all of the data for the 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 that was saved in the step array JSON. This includes the response_type, the content of the response, and a step_id if one was provided. |
instance | Object |
The current instance of web chat |
view:change
Fired when the view state has changed 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 would be fired when the user clicks the launcher to close the launcher and open the main window. Or it would be fired if the user starts a tour where the tour view opens and the main window closes.
When web chat is initially loaded on a page, all views are considered closed and a view:change
event will be fired that reflects the change from this state to the default state for a loaded web chat. This default state depends on a number of factors including whether there is an active session or if openChatByDefault
is being used.
If you are implementing a custom launcher or using a custom element, you will need to listen for this event in order to change the visibility of the custom element or the launcher.
This event is fired after the given view has already become visible (which would be useful, for example, if you wanted to use a custom panel to display a pre-chat form) but it does allow you to cancel (reverse) the change or to alter what views will be visible after the event is complete.
When the main window is opened for the first time, this event will be fired and it will be fired before web chat has loaded the previous conversation data (if any) or before it requests the welcome message. This gives you the opportunity 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 may return a Promise. If it does, web chat will wait for this Promise to resolve before considering the view change to be complete. This is when you may perform actions like displaying a pre-chat form. The Promise would be resolved after the user has completed the form.
If you want to cancel or alter the change, you can 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.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (view:change ) |
|
event.reason | string |
The reason the view was changed. See View change reasons for an explanation of the possible values here. | |
event.cancelViewChange | boolean |
Yes | If true, indicates that the change should be cancelled. Since the new view state is already effective when this event is fired, this property will cause the view state to revert to its previous state. Note that the view change events are not fired when this occurs. |
event.newViewState | Object |
Yes | The state that the view is being changed to. The values in this object may be changed if you want to alter the final view state that web chat will use. See changeView for more information on what's in this object. |
event.oldViewState | Object |
The view state that was in place before the change view operation began. See changeView for more information about the available views. | |
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
Fired before the view state has changed 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 would be fired when the user clicks the launcher to close the launcher and open the main window. Or it would be fired if the user starts a tour where the tour view opens and the main window closes.
When web chat is initially loaded on a page, all views are considered closed and a view:pre:change
event will be fired that reflects the change from this state to the default state for a loaded web chat. This default state depends on a number of factors including whether there is an active session or if openChatByDefault
is being used.
When the main window is opened for the first time, this event will be fired and it will be fired before web chat has loaded the previous conversation data (if any) or before it requests the welcome message. This gives you the opportunity to send a different message first instead of requesting the welcome message in order to display a different first message to the user.
The handler for this event may return a Promise. If it does, web chat will wait 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.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (view:pre:change ) |
|
event.reason | string |
The reason the view was changed. See View change reasons for an explanation of the possible values here. | |
event.cancelViewChange | boolean |
Yes | If true, indicates that the change should be cancelled. Since the new view state is already effective when this event is fired, this property will cause the view state to revert to its previous state. Note that the view change events are not fired when this occurs. |
event.newViewState | Object |
Yes | The state that the view is being changed to. The values in this object may be changed if you want to alter the final view state that web chat will use. See changeView for more information on what's in this object. |
event.oldViewState | Object |
The view state that was in place before the change view operation began. See changeView for more information on what's in this object. | |
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
Fired when the web chat window closes, after the window:pre:close
event.
This is deprecated. Use view:change instead. Also note that this event may not work as expected if you are using the tours feature.
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
Fired when the web chat window closes, before the window:close
event. Returning a Promise here will prevent the web chat window from closing until the promise is resolved.
This is deprecated. Use view:pre:change instead. Also note that this event may not work as expected if you are using the tours feature.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:pre:close ) |
|
event.cancelClose | boolean |
Yes | If true, indicates that the close should be cancelled. |
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
Fired when the chat window is opened. This event is fired before the web chat attempts to load any existing history data or before it requests the welcome message. This can be used to send a different message first if you want to customize the welcome message that is displayed.
This is deprecated. Use view:pre:change instead. Also note that this event may not work as expected if you are using the tours feature.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:pre:open ) |
|
event.reason | string |
The reason the window was opened. See Window open reasons for an explanation of the possible values here. | |
event.cancelOpen | boolean |
Yes | If true, indicates that the open should be cancelled and the window should not be opened. |
instance | Object |
The current instance of web chat |
window:open Deprecated
Fired when the chat window is opened. This event is fired before the web chat attempts to load any existing history data or before it requests the welcome message. This can be used to send a different message first if you want to customize the welcome message that is displayed. 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.
This is deprecated. Use view:change instead. Also note that this event may not work as expected if you are using the tours feature.
Parameter | Type | Assignable | Description |
---|---|---|---|
event | Object |
The event | |
event.type | String |
Event type (window:open ) |
|
event.reason | string |
The reason the window was opened. See Window open reasons for an explanation of the possible values here. | |
event.cancelOpen | boolean |
Yes | If true, indicates that the open should be cancelled. Since the window is already open when this event is fired, this property will cause the window to close. Note that the window close events are not fired when this occurs. |
instance | Object |
The current instance of web chat |
Window open reasons
This is a list of the possible reasons that the web chat window may be opened and the value of the reason
property on the window:open
and window:pre:open
events.
Reason | Description |
---|---|
called_open_window | Indicates the widget was opened by a call to the instance function openWindow or toggleOpen . |
default_launcher | Indicates the user clicked on our built-in launcher button that opened the web chat. |
link | Indicates the widget was opened because a link ID was found that started a specific conversation. See Creating links to web chat for more information. |
open_by_default | Indicates the widget was opened because the openChatByDefault property was set to true |
session_history | Indicates the widget was opened as a result of session history. |
Wildcard (*)
Wildcard event. When any event is fired, callbacks that are subscribed to the wildcard event are called after any subscriptions to the specific event type.
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, we released additional support for the tours feature. Tours adds a new "view" to web chat in addition to the existing launcher and main window "views". Because we now have three views instead of two, the previous methods and events that were used around opening and closing of the main window are now ambiguous when a tour is being used. For this reason, we have deprecated the window related methods and events in favor of a more generic "view change" system that has explicit support for tours.
The current window methods and events are still supported for existing web chats and assistants but are deprecated and will be removed in a future version of web chat. This section is designed to help explain how to do the migration from the window methods and events to the view change ones.
Note that while the window methods and events are supported for existing assistants, if you add tours to your assistant, your window events and methods may no longer work as expected. As such, the window methods and events are not supported if you are also using tours. If you decide to add tours to your assistant, please make sure to update any of your custom code to use the new view change methods and events.
Migrating methods
The openWindow, closeWindow, and toggleOpen methods are now deprecated. The changeView method should be used instead.
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, you will need to examine the current view state of the main window to determine if it should be opened or closed.
// 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 should be used instead.
If you are relying on the reason
property in the window events, you should review the new view change reasons since they are different and make sure 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 });