Instance methods
Instance methods enable your code to interact with or modify an active chat instance at run time.
Contents
Overview
List of methods and properties
Instance method and property details
Instance elements
Instance writeable elements
Custom panels
Overview
The window.watsonAssistantChatOptions.onLoad
method returns an instance of web chat initialized with the specified configuration options. The initialized web chat instance supports runtime utility methods your code can use to do things like render the web chat widget, send a message, or subscribe to events.
Example
<script>
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
onLoad: async (instance) => {
// The instance returned here has many methods on it that are documented on this page. You can assign it to any
// global window variable you like if you need to access it in other functions in your application. This instance
// is also passed as an argument to all event handlers when web chat fires an event.
window.webChatInstance = instance;
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>
List of methods and properties
The following is the list of all the available instance methods and properties.
Method or Property | Description |
---|---|
Messages | |
doAutoScroll | Automatically scrolls to the most recent message in the list. |
restartConversation | Restarts the conversation with the assistant. |
scrollToMessage | Scrolls the web chat messages list to the given message. |
send | Sends the specified message to the assistant. |
updateHistoryUserDefined | Updates the value of a user_defined property in the history of a message. |
Events | |
off | Removes a subscription to an event type. |
on | Subscribes to a type of event. |
once | Subscribes an event handler as a listener for only one occurrence of the specified event type. |
Human agent | |
agentEndConversation Deprecated | Ends the conversation with a human agent. The instance.agentEndConversation method is deprecated. Use instance.serviceDesk.endConversation instead. |
serviceDesk.endConversation | Ends the conversation with a human agent. |
Security and identity | |
destroy | Destroys web chat and removes it from the page. |
destroySession | This method removes all cookie or browser storage related to the current web chat session. |
updateIdentityToken | Updates the JWT identity token. |
Tours | |
tours.endTour Beta | Clears all tour data, closes the tour, and switches to the launcher. |
tours.goToNextStep Beta | Move forward one step in the tour. |
tours.goToStep Beta | Move to the step within the tour that has a matching step_id. |
tours.startTour Beta | Sends a message request then switch to the tour view after receiving the new tour data from the request. |
User interface | |
changeView | Changes the current view state. |
customPanels | Returns an object that can be used to control custom panels. |
elements | A list of elements that web chat provides some limited access to. |
render | Renders the web chat widget on your page. |
requestFocus | When the application is open, an appropriate focusable and visible element will get focus. |
showLauncherGreetingMessage | Sets the time for the greeting message to appear from the launcher. |
updateAssistantInputFieldVisibility | Allows you to hide or show the input field when conversing with the assistant. |
updateBotUnreadIndicatorVisibility | Updates the visibility of the custom unread indicator that appears on the launcher. |
updateCSSVariables | Overrides the configurable CSS variables used to render the web chat. |
updateCustomMenuOptions | Updates the display of custom menu options that appear in the header. |
updateHomeScreenConfig | Updates the configuration for the home screen. |
updateIsTypingCounter | Changes the internal counter that determines whether the "is typing" indicator is shown. |
updateLanguagePack | Updates the language pack used for displaying message strings. |
updateLocale | Changes the current locale in use by the widget. |
updateMainHeaderTitle | Changes the name of the assistant in the header. |
updateLauncherAvatarURL | Updates the launcher avatar image. |
updateLauncherGreetingMessage | Sets the greeting message for the launcher. |
writeableElements | A list of container elements where custom elements can be attached. |
closeWindow Deprecated | Closes the chat window if it is currently open. This is deprecated. Use changeView instead. Also note that this event may not work as expected if you are using the tours feature. |
openWindow Deprecated | Opens the chat window if it is currently closed. This is deprecated. Use changeView instead. Also note that this event may not work as expected if you are using the tours feature. |
toggleOpen Deprecated | Toggles the current open or closed state of the window. This is deprecated. Use changeView instead. Also note that this event may not work as expected if you are using the tours feature. |
Web chat state | |
getIntl | Returns the object that is used by web chat for displaying static translated strings. |
getLocale | Returns the current locale in use by the widget. |
getState | Returns properties representing the current state of the web chat. |
getWidgetVersion | Returns the version number of the widget code. |
Instance method and property details
instance.agentEndConversation()
Ends the conversation with a human agent. This does not request confirmation from the user first. If the user is not connected or connecting to a human agent, this function has no effect. You can determine if the user is connected or connecting by calling getState. Note that this function returns a Promise that only resolves when the conversation has ended; this includes after the agent:pre:endChat and agent:endChat events have been fired and resolved.
Example
const state = instance.getState();
if (state.serviceDesk.isConnected || state.serviceDesk.isConnecting) {
await instance.agentEndConversation();
}
instance.serviceDesk.endConversation()
Ends the conversation with a human agent. This does not request confirmation from the user first. If the user is not connected or connecting to a human agent, this function has no effect. You can determine if the user is connected or connecting by calling getState. Note that this function returns a Promise that only resolves when the conversation has ended; this includes after the agent:pre:endChat and agent:endChat events have been fired and resolved.
Example
const state = instance.getState();
if (state.serviceDesk.isConnected || state.serviceDesk.isConnecting) {
await instance.serviceDesk.endConversation();
}
instance.changeView()
Changes the current view state. This can be used, for example, to open or close the main window or to open or close a tour.
This function has two forms. With the first form, you may pass just the name of the view as a string you want to open. With this form, the passed view with be opened and all the other views will be closed. With the second form, you may pass an object. This object can contain the names of the views you wish to change. The state of each view passed in will be changed to provided state. Any views not passed in will not be changed.
The current view names:
launcher
- the button at the bottom of the screen that is used to open the main windowmainWindow
- the main window of web chat that displays messages with the usertour
- the window that displays the contents of an active tour
This method will fire the view:pre:change and view:change events.
Example
// Opens the main window and closes all the other views.
instance.changeView('mainWindow');
// Opens the main window and closes the launcher. The tour view will remain unchanged.
instance.changeView({ mainWindow: true, launcher: false });
instance.closeWindow()
Closes the chat window if it is currently open, and fires the window:close event.
Example
instance.closeWindow();
instance.destroy()
Destroys the web chat widget. The chat window and chat launcher are both destroyed, and all subscriptions to events are removed. Also, all methods on the instance are removed.
To also keep a subsequently created web chat from trying to continue the previous session, you should also call instance.destroySession before calling this method.
Example
instance.destroy();
instance.destroySession()
Web chat stores information about the current session in the browser. This method removes all browser storage related to the current web chat session. It will also issue a call to the server to remove the session from the server. You can call this method as part of your logout sequence to avoid a subsequent user's web chat trying to reconnect to the previous user's session.
The current instance of web chat should not continue to be used after this call is made. Unless this is being called as the current window is being unloaded, you should also call instance.destroy to destroy the web chat instance and remove it from the page.
Example
instance.destroySession();
instance.doAutoScroll()
Automatically scrolls to the most recent message in the list. This method is helpful when you render a user_defined
response type after the web chat has already completed its autoscroll behavior, and you need the web chat to correct itself.
Example
instance.doAutoScroll();
instance.getIntl()
Returns the object that is used by web chat for displaying static translated strings. This object is an instance of a IntlShape
that is provided by the Format.JS library. You can find the out-of-the-box strings that web chat uses in the languages folder. Make sure to access the files for the version of web chat that you are using.
Note that a new IntlShape
object is created every time the locale or language pack is updated.
Example
const placeholderText = instance.getIntl().formatMessage({ id: 'input_placeholder' });
instance.getLocale()
Returns the current locale in use by the widget.
This method returns a string containing the language code or the language and region codes (for example, ja
or en-gb
).
Example
console.log(instance.getLocale());
instance.getState()
Returns properties representing the current state of the web chat.
Parameter | Type | Description |
---|---|---|
isAssistantInputFieldVisible | Boolean |
Is the input field visible if user is talking to assistant. |
isConnectedWithHumanAgent Deprecated | Boolean |
Is the web chat currently connected with a human agent. This property is deprecated; use serviceDesk.isConnected instead. |
isConnectingWithHumanAgent Deprecated | Boolean |
Indicates if web chat has requested to be connected to a human agent but an agent has not yet joined the conversation. This property is deprecated; use serviceDesk.isConnecting instead. |
isDebugEnabled | Boolean |
Indicates if the debug flag for web chat was set to true . |
isHomeScreenOpen | Boolean |
Is the home screen open. |
isTourActive Beta | Boolean |
Is there currently an active tour. This can be true even if a tour isn't visible. If there is an active tour but the launcher or main chat window are visible then the tour will appear upon launcher click or minimize of the main chat window. |
isWebChatOpen | Boolean |
Is the web chat currently in an open state. |
hasUserSentMessage | Boolean |
Has the user sent a message. |
serviceDesk.isConnected | Boolean |
Is the web chat currently connected with a human agent. |
serviceDesk.isConnecting | Boolean |
Indicates if web chat has requested to be connected to a human agent but an agent has not yet joined the conversation. |
sessionID | String |
The active watsonx Assistant sessionID. |
userID | String |
The current user ID being used by web chat. This can be used to retrieve the anonymous user ID used by web chat if no user ID has been provided by the host page. This ID may not be set until web chat is opened and it is provided by the host page. This value may also change if the host page provides an update to the user ID before a new session has begun. |
viewState | Object |
The current state of all the views. See changeView for a list of the possible view. |
Example
instance.getState();
instance.getWidgetVersion()
Returns the version number of the widget code.
Example
instance.getWidgetVersion();
instance.off()
Removes a subscription to an event type. After you remove a subscription, the callback handler is no longer called for that event type.
This method returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | Method options. | |
options.type | string |
Required | The event type you no longer want to listen for (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Optional | A reference to the callback you want to unsubscribe. Specify this parameter to indicate which callback you want to unsubscribe, if you have subscribed multiple callbacks to the same event type. By default, all subscriptions registered to the event type are removed. |
Example
// Your handler
function handler(event) {
console.log(event);
}
instance.on({ type: 'receive', handler: handler });
instance.on({ type: 'send', handler: handler });
instance.off({ type: 'receive', handler: handler });
instance.off({ type: 'send', handler: handler });
// You can also pass AN ARRAY of objects to the method
instance.on([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.off([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
// You can also just "unsubscribe from all" by not passing a handler
instance.on({ type: 'send', handler: handler });
instance.off({ type: 'send' });
instance.on()
Subscribes to a type of event, using a callback that is called whenever an event of the specified type is fired. You can register as many subscriptions to an event type as you want. Subscriptions are called in order, starting with the first registered.
This method returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | Method options. | |
options.type | string |
Required | The event to listen to (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Required | The callback that will handle the event. |
Example
// Your handler
function handler(event) {
console.log(event);
}
instance.on({ type: 'receive', handler: handler });
instance.on({ type: 'send', handler: handler });
// You can also pass AN ARRAY of objects to the method
instance.on([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.once()
Subscribes an event handler as a listener for only one occurrence of the specified event type. After one event of the specified type is handled, this handler is automatically unsubscribed.
This method returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | Method options. | |
options.type | string |
Required | The event type to listen for (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Required | The callback that will handle the event. See Events. |
Example
function handler(event) {
console.log(event);
}
const mockSendObject = {
input: {
message_type: 'text',
text: 'get human agent'
}
};;
instance.once({ type: 'send', handler: handler });
instance.send(mockSendObject);
// The subscription is now removed.
// You can also pass AN ARRAY of objects to the method
instance.once([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.openWindow()
Opens the chat window if it is currently closed, and fires the window:open event.
Example
instance.openWindow();
instance.requestFocus()
When the application is open, an appropriate focusable and visible element will get focus.
Example
instance.requestFocus();
instance.render()
Renders the web chat widget on your page.
This method returns a Promise that succeeds if the widget successfully renders.
Example
instance.render().then(function() {
console.log('It worked!')
}).catch(function(e) {
console.error(e);
});
instance.restartConversation()
Restarts the conversation with the assistant and ends any conversation with a human agent. This will clear all of the current assistant messages from the main bot view and cancel any outstanding messages. This will also delete the current assistant session which will force a new session to start on the next message.
This method will also fire the pre:restartConversation and restartConversation events.
Once the restart is complete, web chat will switch to the home screen or request the welcome message to be displayed again.
Example
instance.restartConversation();
instance.scrollToMessage()
Scrolls the web chat messages list to the given message. The top of the message will be scrolled to the top of the message list. The ID of the message can be obtained using one of the receive
, pre:receive
, send
, pre:send
, history:begin
or history:end
events depending on where the message came from.
Parameter | Type | Description |
---|---|---|
messageID | String |
The ID of the message |
animate (optional) | boolean |
Indicates if the scrolling should be animated. |
Example
instance.scrollToMessage('8cf22fcd-f3d1-4eee-9aea-26d14e87e481');
instance.send()
Sends the specified message to the assistant. This results in pre:send and send events being fired.
This method returns a Promise that resolves successfully when the message is successfully sent.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object or String |
Required | A v2 message request object or a string. If a string is provided, a v2 message object will be created automatically that uses the given string as the text of the message. (For more information, see the API Reference.) | |
options | Object |
Method options. | ||
options.silent | Boolean |
Whether the message should be hidden from the UI. If this option is set to true , the message is sent to the assistant, but does not appear in the web chat UI. |
||
options.skipPause | Boolean |
Indicates if the forced pause displayed with the response should be skipped. By default, web chat will insert a pause to produce a delay of 1 second after the response has been received. This is to give the bot a more natural, conversational feeling to it. This value defaults to true if this function is called while the web chat is closed. |
Examples
A simple text message.
instance.send('get a human agent');
A message request using the message request object format and with a silent option so the message request is not visible to the user. Note, send always returns a Promise but it's particularly important when a silent message is sent to catch any errors from the Promise and notify the user about them since it may not be obvious in the chat that the message has failed.
const sendObject = {
input: {
message_type: 'text',
text: 'get a human agent'
}
};
const sendOptions = {
silent: true
}
instance.send(sendObject, sendOptions).catch(console.error);
A message that sets a context variable. Replace ['main skill'].user_defined
with ['actions skill'].skill_variables
if you are using Actions instead of Dialog.
const sendObject = {
input: {
message_type: 'text',
text: 'get a human agent'
},
context: {
skills: {
['main skill']: {
user_defined: {
custom_var: 'My custom variable',
}
}
}
}
};
instance.send(sendObject);
instance.showLauncherGreetingMessage()
showLauncherGreetingMessage() is used to control the timing of when the greeting message appears. The default behavior is that the greeting message will appear after 15 seconds. If the greeting message is already visible then any new time will be ignored. If the greeting message was visible to the user when the page was changed or reloaded then the greeting message will still be visible on reload. The updated timing will not be saved in session storage, if the user changes pages or reloads the page before the greeting message has appeared then the updated timing needs to be set again. This can not be used to change the greeting text of the launcher. If you want to change the text use instance.updateLauncherGreetingMessage()
Parameter | Type | Required | Description |
---|---|---|---|
time | Number |
Optional | The number of milliseconds until the launcher should display the greeting message. For example passing 4000 would imply that the greeting message should be shown four seconds from now. If no time is passed then the greeting message will appear immediately. |
launcherType | String |
Optional | There are two different launchers that will appear depending on the end users device type, a desktop and a mobile launcher. launcherType can be used to specify which launcher the new timing should be set for, valid options are either mobile or desktop . If no launcherType is passed then the timing will be set for both. |
Example
// To show the desktop launcher in 4s (the mobile launcher will show at the original 15s interval).
instance.showLauncherGreetingMessage(4000, 'desktop')
// To show the mobile launcher in 6s (the desktop launcher would still plan to show in 4s).
instance.showLauncherGreetingMessage(6000, 'mobile')
// To show both the desktop and mobile launcher 8s from now (the previous timers would be cleared).
instance.showLauncherGreetingMessage(8000)
instance.toggleOpen()
Toggles the current open or closed state of the window.
Example
instance.toggleOpen();
instance.tours.endTour() Beta
This method clears all tour data, closes the tour, and switches to the launcher. When the launcher is clicked on by the user the main chat window will open. From the chat window the user can start the tour again with the tour card.
instance.tours.goToNextStep() Beta
This method will move to the next step in the tour. When the next step is switched to the tour:step event will fire.
instance.tours.goToStep() Beta
This method accepts a string for the stepId
that the tour should go to. This stepId should be defined in the tour json as a step_id
string. When the new step is switched to the tour:step event will fire.
Example
// Switch to the step in the tour that is labeled as step_id: "welcome_3" in the tour json.
instance.tours.goToStep('welcome_3');
instance.tours.startTour() Beta
This method accepts a message
string that will be sent to the back-end in order to get data for a new tour. Once the new tour data is received the tour view is automatically switched to. When the tour is switched to the tour:start event fires.
Example
// Send a message that corresponds to a "welcome tour" action and will return tour data to be show.
instance.tours.startTour('welcome tour');
instance.updateAssistantInputFieldVisibility()
Allows you to hide or show the input field when conversing with the assistant. This is useful if your assistant only requires input via buttons or other constrained input. This does not apply to the input field for conversing with a human agent.
Parameter | Type | Description |
---|---|---|
shouldBeVisible | Boolean |
If the input fields to write to the assistant should be visible. |
Example
instance.updateAssistantInputFieldVisibility(true); // Shows input field.
instance.updateAssistantInputFieldVisibility(false); // Hides input field.
instance.updateBotUnreadIndicatorVisibility()
Updates the visibility of the custom unread indicator that appears on the launcher. This indicator will appear as an empty circle on the launcher and will remain visible until web chat is opened.
This indicator is in addition to the indicator for unread messages from a human agent. If there are any unread agent messages, a circle will appear with the unread count inside of it and it will appear regardless if this method is called.
You can adjust the colors of this indicator by using the updateCSSVariables method.
Parameter | Type | Required | Description |
---|---|---|---|
isVisible | boolean |
Required | A value of true will show the indicator and false will hide it (unless there are unread agent messages). |
Example
// Show the indicator.
instance.updateBotUnreadIndicatorVisibility(true);
// Hide the indicator.
instance.updateBotUnreadIndicatorVisibility(false);
instance.updateCSSVariables()
Overrides the configurable CSS variables used to render the web chat. You can pass in as many variables as you want to override. The values you specify are merged with the existing settings. You can also visit the section on Theming for more information.
Warning: since web chat gives you plenty of hooks to amend and change content, and web chat itself is just HTML, CSS and JavaScript, it can be tempting to manipulate content outside of what it allows by default. We highly recommend you do not do that to avoid unintended issues as web chat deploys new releases.
Example
instance.updateCSSVariables({
'BASE-z-index': '8000',
'BASE-font-family': '"Times New Roman", Times, serif',
'$focus': '#ff0000'
});
Customizable variables
Parameter | Type | Default | Description |
---|---|---|---|
BASE-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family used by web chat. |
BASE-header-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family used by web chat in the header. |
BASE-height | CSS height value |
640px | The default value web chat will set its height to. Web chat also has a default max-height of 640px on desktop devices. If you want a height greater than this, you will need to change BASE-max-height as well. |
BASE-max-height | CSS height value |
640px | The default max value web chat will set its height to on desktop devices. On mobile devices, web chat will be sized to fill the screen. |
BASE-width | CSS width value |
380px | The default value the web chat will set its width to. On mobile screens, or if you are using a custom element, the web chat will grow to the size of the respective container instead of this width. |
BASE-z-index | Number |
99999 | The z-index on your website that the web chat is assigned to. |
HOME_SCREEN-greeting-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family used by main greeting message on the home screen. |
UNREAD-INDICATOR-color-background | Hex color code |
#da1e28 | The background color of the launcher unread indicator. |
UNREAD-INDICATOR-color-text | Hex color code |
#ffffff | The color of the text that appears on the launcher unread indicator. |
$chat-button | Hex color code |
#000000 in white and g10 themes, #ffffff in g90 and g100 themes | The border and text color of the rounded buttons with transparent backgrounds that are used throughout the home screen and main chat window. These chat buttons are in beta within carbon so these properties aren't currently documented within their docs. |
$chat-button-hover | Hex color code |
#8c8c8c1f in white and g10 themes, #8c8c8c29 in g90 and g100 themes | The background color of the rounded buttons with transparent backgrounds when hovered. |
$chat-button-text-hover | Hex color code |
#525252 in white and g10 themes, #f4f4f4 in g90 and g100 themes | The text color of the rounded buttons with transparent backgrounds when hovered. |
$chat-button-selected | Hex color code |
#8c8c8c33 in white and g10 themes, #8c8c8c3d in g90 and g100 themes | The background color when one of the rounded buttons with transparent backgrounds is selected. |
$chat-button-active | Hex color code |
#8c8c8c80 in white and g10 themes, #8c8c8c66 in g90 and g100 themes | The background color when one of the rounded buttons with transparent backgrounds is active. |
$chat-button-text-selected | Hex color code |
#525252 in white and g10 themes, #c6c6c6 in g90 and g100 themes | The text color when one of the rounded buttons with transparent backgrounds is selected. |
Customizable launcher variables
You can override the pre-configured color variables for the web chat launcher and desktop launcher expanded message.
Parameter | Type | Description |
---|---|---|
LAUNCHER-color-avatar | Hex color code |
The color of the default launcher avatar. |
LAUNCHER-color-background | Hex color code |
The background color of the default launcher. |
LAUNCHER-color-background-active | Hex color code |
The background color of the default launcher in the active state. |
LAUNCHER-color-background-hover | Hex color code |
The background color of the default launcher in the hover state. |
LAUNCHER-color-focus-border | Hex color code |
The border color of the launcher in the focus state. |
LAUNCHER-EXPANDED-MESSAGE-color-background | Hex color code |
The background color of the desktop launcher expanded message. |
LAUNCHER-EXPANDED-MESSAGE-color-background-active | Hex color code |
The background color of the desktop launcher expanded message in the active state. |
LAUNCHER-EXPANDED-MESSAGE-color-background-hover | Hex color code |
The background color of the desktop launcher expanded message in the hover state. |
LAUNCHER-EXPANDED-MESSAGE-color-text | Hex color code |
The text color of the desktop launcher expanded message. |
LAUNCHER-EXPANDED-MESSAGE-color-focus-border | Hex color code |
The border color of the desktop launcher expanded message in the focus state. |
LAUNCHER-MOBILE-color-text | Hex color code |
The text color of the mobile launcher message. |
Example
instance.updateCSSVariables({
'LAUNCHER-color-background': '#525252',
'LAUNCHER-color-background-hover': '#3d3d3d',
'LAUNCHER-color-background-active': '#1f1f1f',
'LAUNCHER-color-focus-border': '#ffffff',
'LAUNCHER-color-avatar': '#ffffff',
'LAUNCHER-EXPANDED-MESSAGE-color-background': '#ffffff',
'LAUNCHER-EXPANDED-MESSAGE-color-background-hover': '#ebebeb',
'LAUNCHER-EXPANDED-MESSAGE-color-background-active': '#cccccc',
'LAUNCHER-EXPANDED-MESSAGE-color-focus-border': '#000000',
'LAUNCHER-EXPANDED-MESSAGE-color-text': '#000000',
'LAUNCHER-MOBILE-color-text': '#000000',
});
await instance.render();
Customizable theming variables
For a complete list of theming variables and their default values, see the Carbon Design System documentation. To customize the appearance of your web chat, use the instance.updateCSSVariables() method to override the theming variables you want to change. Color values must be in hexadecimal format.
Example
instance.updateCSSVariables({ '$focus': '#ff0000' });
await instance.render();
instance.updateCustomMenuOptions()
Updates the display of custom menu options that appear in the header. These options are displayed in a hamburger menu that appears in the top left corner of the header. This method may be called at any point to change the current set of options. Each option may be configured with a custom callback function that will be called when the option is selected.
Parameter | Type | Required | Description |
---|---|---|---|
options | array |
Required | An array of options to display. Each value of the array is an object that has the text to display for the menu option label as well as a function that is the click handler to be called when the option is selected. |
options[n].text | string |
Required | The text to display for this option. |
options[n].handler | function |
Required | A function that will be called when the option is selected. |
Example
instance.updateCustomMenuOptions([
{ text: 'Bot option 1', handler: () => console.log(`Selected Bot option 1`) },
{ text: 'Bot option 2', handler: () => console.log(`Selected Bot option 2`) },
]);
instance.updateHistoryUserDefined()
updateHistoryUserDefined() provides a way to save state for any message response. This saved state will then be available in the history.user_defined section of the message response on reload. The data will only be saved for the duration of the user's session; once the session expires the data will be deleted.
Parameter | Type | Description |
---|---|---|
messageID | String |
The messageID of the message response the data is being saved for. Depending on the event this method is being used within the messageID may come from different sources. For example in receive the id is available in event.data.id , however in userDefinedResponse the id can be found at event.data.fullMessage.id . |
data | Anything |
The data to be saved. Once it's been passed to web chat the data is frozen and can't be updated. However you can call this method again to save more state related to a message response. If this method is called multiple times for the same message then the data is merged in with any existing data if it's an object. It doesn't replace the entire object. |
For an example of this method in action look at the "Example with session history" in the userDefinedResponse section.
Warning: there is a limit of 20 calls per messageID for this method.
instance.addNotification() Deprecated
The addNotification()
method provides a way to notify the user in a way consistent with web chat of the results of actions that have been taken.
Parameter | Type | Description | Required |
---|---|---|---|
notification.groupId | String | The group id to associate with one or more notifications. You can use this to group notifications and remove them at once. See instance.notifications.removeNotifications()) for more information. | Optional |
notification.kind | 'error', 'info', 'success', or 'warning' | The type of notification to be shown. | Required |
notification.title | String |
The title that will be displayed in the notification. | Required |
notification.message | String |
The message that will be displayed in the system. | Required |
notification.actionButtonLabel | String |
The text displayed on an optional action button . |
Optional |
notification.onActionButtonClick | Function |
A function to call when the action button is clicked. The notification will dismiss when the button is clicked. |
Optional |
notification.onCloseButtonClick | Function |
A function to call when the close button is clicked. |
Optional |
Example
instance.addNotification({
kind: 'success',
title: 'Success',
message: 'You have successfully paid your bill.'
});
instance.addNotification({
kind: 'error',
title: 'Error',
message: 'Your bill was unable to be paid.',
actionButtonLabel: 'Contact us',
onActionButtonClick: () => { // Do something, notification will close on click. }
});
instance.updateHomeScreenConfig
Turn on and off the home screen feature, and dynamically update the home screen content. This is useful if you want to have different conversation starters or welcome text on different pages of your website.
This can also be used to control the home screen background. The home screen currently supports two options for background gradients; either a top corner out gradient, or a gradient that goes from the bottom up. You can choose between these two options, and whether or not to enable the background gradient, by editing the background_gradient
object within the homeScreenConfig.
Example
instance.updateHomeScreenConfig({
is_on: true,
greeting: 'Welcome! Please ask us a question.',
starters: {
is_on: true,
buttons: [
{
label: 'Open a new brokerage account',
},
{
label: 'Open a new savings account',
},
{
label: 'Open a new checking account',
}
]
},
background_gradient: {
is_on: true,
gradient_direction: 'bottom_up'
}
});
Parameter | Type | Required | Description |
---|---|---|---|
homeScreenConfig | Object |
Required | The configuration object for a home screen. |
homeScreenConfig.is_on | boolean |
Optional | If true , will show a home screen. |
homeScreenConfig.greeting | text |
Optional | Text to introduce your assistant. |
homeScreenConfig.starters | Object |
Optional | Configuration for the conversation starter buttons. |
homeScreenConfig.starters.is_on | boolean |
Optional | If true will show conversation starter buttons. |
homeScreenConfig.starters.buttons[] | Object[] |
Optional | An array of conversation starter button configurations. |
homeScreenConfig.starters.buttons[].label | string |
Optional | The text to display to the user in the button. This text will be sent to your assistant when the button is pressed. |
homeScreenConfig.bot_avatar_url | string |
Optional | The image url to load as the bot avatar in home screen. |
homeScreenConfig.custom_content_only | boolean |
Optional | Hides avatar, greeting message and starters so you can provide you own custom home screen. |
homeScreenConfig.background | 'none', 'solid', 'top_corner_out', 'bottom_up' | Optional | Configuration for the background. 'none' leaves the home screen background the same color as the chat background. 'solid' uses the accent color for the home screen background. 'top_corner_out' and 'bottom_up' are both gradient backgrounds for the home screen that fade from the accent color to the chat background color. These fades start from either the top corner, or the bottom of the home screen, depending on which gradient option is used. |
homeScreenConfig.background_gradient Deprecated | Object |
Optional | Configuration for the background gradient. This is deprecated. Use background instead. |
homeScreenConfig.background_gradient.is_on Deprecated | boolean |
Optional | If true , will add a background gradient to the home screen. If gradient_direction is not specified then the gradient will come from the top corner out by default. This is deprecated. Use background instead. |
homeScreenConfig.background_gradient.gradient_direction Deprecated | 'top_corner_out', 'bottom_up' | Optional | Two different options for the direction of the background gradient. This direction will only be applied if the background_gradient.is_on option is enabled. This is deprecated. Use background instead. |
instance.updateIsTypingCounter()
Changes the internal counter that determines whether the "is typing" indicator is shown. This indicator is an animated "..." that lets the user know the assistant is "typing" a message. This indicator is shown based on an internal counter that is increased whenever something that qualifies as "is typing" occurs and it is decreased when that action is complete. The indicator is shown as long as this counter is greater than zero. This function can be used to increase or decrease this counter (but not below zero).
To increase the counter, pass the argument increase
to the method. To decrease the counter, pass the argument decrease
to the method.
Care should be made to ensure that if you increase the counter, you always decrease it, even in the event of an error. If you fail to decrease the counter, the indicator will become stuck permanently showing.
Example
// Show the indicator.
instance.updateIsTypingCounter('increase');
// Hide the indicator.
instance.updateIsTypingCounter('decrease');
instance.updateMainHeaderTitle()
Updates the string shown in the header of the chat to signify the name of the assistant. This value defaults to the name of your assistant generated inside the web chat config screen inside watsonx Assistant. If you have the AI theme turned on, it defaults to blank.
Example - Adding a new title
instance.updateMainHeaderTitle('Larry the Assistant');
Example - Setting an empty title
instance.updateMainHeaderTitle();
instance.updateLanguagePack()
Updates the current language pack with the values from the provided language pack. This language pack does not need to be complete; only the strings it contains are updated, and all other strings remain unchanged. Variables used within a value string of the current language pack can be used in your updated strings. If you need to make an update based on the user's locale (e.g. British English vs US English), use getLocale to identify the current locale.
See Languages for more information.
Example
const customLanguagePack = {
errors_communicating: 'Oops, something went wrong. Refresh to try again.'
};
instance.updateLanguagePack(customLanguagePack);
instance.updateIdentityToken()
Warning: you must turn security on inside your web chat instance configuration page inside watsonx Assistant for this method to work.
The function takes a signed JWT identity token used to verify the data you send to watsonx Assistant. The passed JWT is available in context at context.integrations.chat.private.jwt
as the base64 encoded string. See the documentation on how to access this variable in actions. This way you can optionally reuse this JWT to call other services from webhooks. The data inside context.integrations.chat.private
will not be returned to the browser when a message is received.
Parameter | Type | Required | Default |
---|---|---|---|
identityToken | JWT |
Required |
instance.updateLauncherAvatarURL()
updateLauncherAvatarURL() allows you to modify the default web chat launcher avatar with a custom image. The avatar will be rendered in 32 x 32 pixels.
Example
instance.updateLauncherAvatarURL('CUSTOM_AVATAR_URL');
instance.updateLauncherGreetingMessage()
updateLauncherGreetingMessage() provides a way to update the greeting text of the launcher. This will override any text already configured for the launcher within watsonx Assistant. We recommend limiting the number of characters to 65 on desktop, and 45 on mobile, in order to avoid truncation. The updated text will not be saved in session storage, if the user changes pages or reloads the page then the updated text needs to be set again. This does not cause the greeting message to be displayed. If you want to show the greeting message, use instance.showLauncherGreetingMessage()
Parameter | Type | Required | Description |
---|---|---|---|
greetingMessage | String |
Required | The new greeting text for the launcher. |
launcherType | String |
Optional | There are two different launchers that will appear depending on the end users device type, a desktop and a mobile launcher. launcherType can be used to specify which launcher the new greeting text should be set for, valid options are either mobile or desktop . If no launcherType is passed then the greeting text will be set for both. |
Example
// To update desktop text only.
instance.updateLauncherGreetingMessage('launcher text desktop', 'desktop')
// To update mobile text only.
instance.updateLauncherGreetingMessage('launcher text mobile', 'mobile')
// To update both desktop and mobile text.
instance.updateLauncherGreetingMessage('launcher text')
instance.updateLocale()
Changes the current language and locale in use by web chat. See Languages for more information. By default, the locale is US English (en-us
).
The locale will control the default language strings and the format of any dates shown by web chat that it generated on its own (not dates you generate in your dialog skill, for instance). If you simply want to change the web chat to use spanish, you can update the locale to es
. If you want more fine-grained control over individual strings, see instance.updateLanguagePack. If you change the locale after updating individual language strings, you will lose your changes to the individual strings. It is recommended you call the updateLocale
method before you call instance.render()
.
This method returns a Promise that succeeds if the widget successfully updates the locale.
Note: after this function is called, the context.global.system.locale
context variable will be set to this value on the next message that is sent to the assistant.
Example
await instance.updateLocale('fr');
instance.updateUserID()
This method is only available if you are not using an identity token. This userID is the userID used for billing purposes. The userID is also sent as the customer_id
section in the X-Watson-Metadata
HTTP header and can be used to make requests to delete user data. Because of this, the syntax must meet the requirements for header fields as defined in RFC (all visible ASCII characters).
The updateUserID method sets the ID of the current user who is interacting with the web chat widget at run time. This method can be used to set the userID only if it has not previously been set. It cannot be used to change to a different userID. This userID can be used to delete the user's data on request. Learn more
This userID is also used for billing purposes. If you do not supply a userID, we will generate one to ensure proper billing. Learn more
There can only be one userID per session. If you're not sure if there is an active session, or if you're unsure if a previous session is complete, you can call instance.destroySession() and then run this command to start a new session with the new userID.
The userID is available under context.integrations.channel.private.user.id
.
Warning: do not use personally identifiable information as the userID like an email address.
Example
instance.updateUserID('some-user-id-that-is-not-identifiable');
Instance elements
instance.elements.getMainWindow()
This function provides access to the main window of web chat. If you are using a custom element to contain web chat, using these functions will be required to show or hide the main window or to apply animations.
addClassName()
Adds the given classname to the main window element.
Argument | Type | Description |
---|---|---|
className | String |
The name of the class to add to the main window element. |
removeClassName()
Removes the given classname from the main window element. Only classnames added with addClassName
can be removed.
Argument | Type | Description |
---|---|---|
className | String |
The name of the class to remove from the main window element. |
Example
instance.elements.getMainWindow().addClassName('HideWebChat');
instance.elements.getMessageInput()
This function provides access to the input field that appears at the bottom of the main messages area of the main window. This field is a different object than the field that appears on the home screen.
getHTMLElement()
Returns the raw DOM element (text area) that is the input field. You can attach listeners to this element to provide custom behavior to the field. For example, you can add a keydown
listener that could navigate through a type-ahead popup using the arrow keys. You can also access the value
property of the element to get the current value in the field.
While you can add input
and change
listeners to this field, those listeners are not fired in some cases. For example, if web chat internally changes the value of the field (which happens when it clears the field after the user sends a message), these events are not fired. In order to ensure that you always get any change to the value of the field, use the addChangeListener function instead.
Setting the value
property of the element directly will also not work as expected. Doing so will not trigger the internal events that web chat needs to respond to the change (such as enabling the send button). You should instead use the setValue elements function instead.
Also note that you cannot access the input field before it has been rendered by web chat. This does not occur until after chat:ready has fired. You should wait for this event using once before attempting to access the element.
setValue()
Sets the value of the input field. You should use this instead of setting the value
property directly on the HTML DOM element.
Argument | Type | Description |
---|---|---|
value | String |
The value to set in the input field. |
setEnableEnterKey()
Changes whether the enter key is handled by web chat. The default behavior of web chat is that when the user presses the enter key inside the input field, it will send the contents of the field to the assistant or an agent. Setting this value to false will disable this behavior. This can allow you to add custom logic when the user presses this key (for example, if the user selects a highlighted value from a type-ahead popup).
Argument | Type | Description |
---|---|---|
isEnabled | boolean |
With a value of true , web chat will send the message when enter is pressed. With a value of false , web chat will not. |
addChangeListener()
Adds a change listener to the input field that will fire whenever the value in the field changes. This will fire even in cases where a change
or input
DOM event would not.
Argument | Type | Description |
---|---|---|
listener | Function |
The listener to add. The listener will be passed a single argument which is the new value of the input field. |
removeChangeListener()
Removes a change listener from the input field.
Argument | Type | Description |
---|---|---|
listener | Function |
The listener to remove. |
Example
instance.once({ type: 'chat:ready', handler: () => {
const messageInput = instance.elements.getMessageInput();
messageInput.setValue('Default value');
messageInput.getHTMLElement().addEventListener('keydown', event => console.log('Got keydown', event));
messageInput.addChangeListener(value => console.log('You typed', value));
}});
instance.elements.getHomeScreenInput()
This function provides access to the input field that appears at the bottom of the home screen. This field is a different object than the field that appears on the main message area. This function returns an object that has the same functions as getMessageInput.
Instance writeable elements
Web chat provides elements available in different parts of the web chat for you to provide custom HTML content. You can directly write to these elements or, if you are using advanced frameworks like React or Angular, you can write to these elements as portals from your own application.
Example
instance.writeableElements.welcomeNodeBeforeElement.innerHTML = '<div class="my-awesome-class">Disclaimer text...</div>';
You would need to wrap the CSS rules of .my-awesome-class
inside #WACContainer.WACContainer
inject into the <head>
of your document, or make use of web components or ShadowRoot and inject your CSS rules inline in the writeable element to apply your styles.
Element name | Description |
---|---|
headerBottomElement | Add content to the bottom of the main header when talking with the Assistant. Useful for adding dismissible banners or other content you want to remain visible even when a user scrolls. |
welcomeNodeBeforeElement | Add content above the welcome node. Useful for further introductions of your assistant or disclaimers. |
homeScreenHeaderBottomElement | Add content to the home screen below the header and above the rest of the homescreen content. Useful for replacing the avatar with custom content and leaving the rest of the homescreen as configured. |
homeScreenAfterStartersElement | Add content to the home screen below any conversation starters. Useful for additional non-text content to introduce your assistant, advertisements, or alternate forms of customer support. You can use this inconjuction with the custom_content_only option in the homescreen configuration object to take complete control of the homescreen. |
beforeInputElement | Add content that appears after the messages area when talking with the Assistant and before the input field. |
aiTooltipAfterDescriptionElement | If using the Carbon for AI theme, this element will appear below the title and description in the AI tooltip in the header of the web chat. Useful for adding additional non-text content to explain how your assistant works. |
Custom panels
Web chat provides access to panels that can take up the whole web chat window and that can contain fully custom content. To get a custom panel, use the instance.customPanels.getPanel()
instance method.
instance.customPanels
Returns an object that can be used to control custom panels.
Method | Description |
---|---|
instance.customPanels.getPanel() | Returns a custom panel instance. |
Custom Panel Instance
The following is the list of all the available custom panel instance methods.
Method | Description |
---|---|
open |
Opens the custom panel with basic config options that change the look and feel of the panel. |
close |
Closes the custom panel if it is open. |
The following is the list of all the available custom panel instance properties.
Property | Description |
---|---|
hostElement |
Returns the element that will host your content and display it in the panel. |
customPanel.open()
This method opens the custom panel and accepts configuration options for the custom panel. It also fires a customPanel:pre:open event when its opening animation has started. Once the opening animation has ended it fires a customPanel:open event.
Example
const customPanel = instance.customPanels.getPanel();
const panelOptions = {
title: 'My custom panel',
};
customPanel.open(panelOptions);
Optional properties for the options
object:
Parameter | Type | Default | Description |
---|---|---|---|
disableAnimation | Boolean |
false | Disables the panel's opening/closing animations. |
disableDefaultCloseAction | Boolean |
false | Disables the default action that is taken when the close or close-and-restart buttons are clicked. The default action closes web chat and disabling this will cause the button to not do anything. You can then override the button behavior by using the onClickClose or onClickCloseAndRestart callback. |
hideBackButton | boolean |
false | Indicates if the back button in the panel header should be hidden. This button closes the custom panel and sends the user back to the previous panel. |
hideCloseAndRestartButton | Boolean |
false | Indicates if the close-and-restart button in the panel header should be hidden. Note that this value only applies if the showCloseAndRestartButton flag is enabled in the top level web chat config. |
hideCloseButton | Boolean |
false | Indicates if the close/minimize button in the panel header should be hidden. This button closes and minimizes all of the web chat window. Note that this value is ignored if the top-levelhideCloseButton value for all of web chat is true . |
hidePanelHeader | Boolean |
false | Indicates if the entire panel header should be hidden. |
onClickBack | Function |
This callback is called when the back button is clicked. | |
onClickClose | Function |
This callback is called when the close button is clicked. This is called even if disableDefaultCloseAction is set to true. |
|
onClickCloseAndRestart | Function |
This callback is called when the close-and-restart button is clicked. This is called even if disableDefaultCloseAction is set to true. This is only called after the user clicks then button and then confirms they wish to end the conversation. |
|
title | String |
The title to display in the custom panel header. |
customPanel.close()
This method closes the custom panel and fires a customPanel:pre:close event when its closing animation starts. Once the closing animation has ended it fires a customPanel:close event.
Example
const customPanel = instance.customPanels.getPanel();
customPanel.close();
customPanel.hostElement
The host element where you can place your content to display within the custom panel.
Example
const customPanel = instance.customPanels.getPanel();
customPanel.hostElement.innerHTML = '<div class="content-class">My awesome content!</div>';
You would need to wrap the CSS rules of .content-class
inside #WACContainer.WACContainer
inject into the <head>
of your document, or make use of web components or ShadowRoot and inject your CSS rules inline in the writeable element to apply your styles.