Skip to main contentWatson Assistant web chat

Instance methods

Instance methods enable your code to interact with or modify an active web chat instance at run time.

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: function(instance) {
      // The instance returned here has many methods on it we will document 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.
      instance.render();
      window.WebChatInstance = instance;
    }
  };

  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>

A web chat instance's methods are broken up into the following sections: Chat Window, Home Screen, Security, Theming, Events, Languages, CustomPanels, Tours, and Miscellaneous.

List of methods and properties

The following is the list of all the available instance methods.

MethodDescription
agentEndConversationEnds the conversation with a human agent.
changeViewChanges the current view state.
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.
destroyDestroys web chat and removes it from the page.
destroySessionThis method removes all cookie or browser storage related to the current web chat session.
doAutoScrollAutomatically scrolls to the most recent message in the list.
getIntlReturns the object that is used by web chat for displaying static translated strings.
getLocaleReturns the current locale in use by the widget.
getStateReturns properties representing the current state of the web chat.
getWidgetVersionReturns the version number of the widget code.
offRemoves a subscription to an event type.
onSubscribes to a type of event.
onceSubscribes an event handler as a listener for only one occurrence of the specified event type.
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.
renderRenders the web chat widget on your page.
requestFocusWhen the application is open, an appropriate focusable and visible element will get focus.
restartConversationRestarts the conversation with the assistant.
scrollToMessageScrolls the web chat messages list to the given message.
sendSends the specified message to the assistant.
showLauncherGreetingMessageSets the time for the greeting message to appear from the launcher.
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.
updateAssistantInputFieldVisibilityAllows you to hide or show the input field when conversing with the assistant.
updateCSSVariablesOverrides the configurable CSS variables used to render the web chat.
updateHistoryUserDefinedUpdates the value of a user_defined property in the history of a message.
updateHomeScreenConfigUpdates the configuration for the home screen.
updateCustomMenuOptionsUpdates the display of custom menu options that appear in the header.
updateIdentityTokenUpdates the JWT identity token.
updateIsTypingCounterChanges the internal counter that determines whether the "is typing" indicator is shown.
updateLanguagePackUpdates the language pack used for displaying message strings.
updateLauncherAvatarURLUpdates the launcher avatar image.
updateLauncherGreetingMessageSets the greeting message for the launcher.
updateLocaleChanges the current locale in use by the widget.
updateBotUnreadIndicatorVisibilityUpdates the visibility of the custom unread indicator that appears on the launcher.
updateUserIDUpdates the user ID.

The following is the list of all the available instance properties.

PropertyDescription
customPanelsReturns an object that can be used to control custom panels.
elementsA list of elements that web chat provides some limited access to.
writeableElementsA list of container elements where custom elements can be attached.
tours
Beta
A set of methods that can be used to manipulate the tour view.

Chat Window

Render, open and close the Chat Window.

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.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.openWindow()

Opens the chat window if it is currently closed, and fires the window:open event.

Example

instance.openWindow();

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 any 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 window
  • mainWindow - the main window of web chat that displays messages with the user
  • tour - 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.toggleOpen()

Toggles the current open or closed state of the window.

Example

instance.toggleOpen();

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.

ParameterTypeDescription
shouldBeVisibleBooleanIf 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.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.requestFocus()

When the application is open, an appropriate focusable and visible element will get focus.

Example

instance.requestFocus();

instance.restartConversation()

Restarts the conversation with the assistant. This does not make any changes to a 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 clear the current assistant session which will force a new session to start on the next message.

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 obtain using one of the receive, pre:receive, send, pre:send, history:begin or history:end events depending on where the message came from.

ParameterTypeDescription
messageIDStringThe ID of the message
animate (optional)booleanIndicates if the scrolling should be animated.
Example

instance.scrollToMessage('8cf22fcd-f3d1-4eee-9aea-26d14e87e481');

Theming

By using predefined themes and by customizing CSS variables, you customize the appearance of your web chat to match your brand.

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.

Example

instance.updateCSSVariables({
  'BASE-z-index': '8000',
  'BASE-font-family': '"Times New Roman", Times, serif',
  '$focus': '#ff0000'
});
instance.render();

Customizable variables

ParameterTypeDefaultDescription
BASE-font-familyString'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serifThe font family used by web chat.
BASE-header-font-familyString'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serifThe font family used by web chat in the header.
BASE-heightCSS height value640pxThe 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-heightCSS height value640pxThe 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-widthCSS width value360pxThe 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-indexNumber99999The z-index on your website that the web chat is assigned to.
HOME_SCREEN-greeting-font-familyString'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serifThe font family used by main greeting message on the home screen.
UNREAD-INDICATOR-color-backgroundHex color code#da1e28The background color of the launcher unread indicator.
UNREAD-INDICATOR-color-textHex color code#ffffffThe color of the text that appears on the launcher unread indicator.

Customizable launcher variables

You can override the pre-configured color variables for the web chat launcher and desktop launcher expanded message.

ParameterTypeDescription
LAUNCHER-color-avatarHex color codeThe color of the default launcher avatar.
LAUNCHER-color-backgroundHex color codeThe background color of the default launcher.
LAUNCHER-color-background-activeHex color codeThe background color of the default launcher in the active state.
LAUNCHER-color-background-hoverHex color codeThe background color of the default launcher in the hover state.
LAUNCHER-color-focus-borderHex color codeThe border color of the launcher in the focus state.
LAUNCHER-EXPANDED-MESSAGE-color-backgroundHex color codeThe background color of the desktop launcher expanded message.
LAUNCHER-EXPANDED-MESSAGE-color-background-activeHex color codeThe background color of the desktop launcher expanded message in the active state.
LAUNCHER-EXPANDED-MESSAGE-color-background-hoverHex color codeThe background color of the desktop launcher expanded message in the hover state.
LAUNCHER-EXPANDED-MESSAGE-color-textHex color codeThe text color of the desktop launcher expanded message.
LAUNCHER-EXPANDED-MESSAGE-color-focus-borderHex color codeThe border color of the desktop launcher expanded message in the focus state.
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',
});
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' });
instance.render();

Instance Elements

The web chat instance provides elements and writeableElements objects that give you access to certain elements within web chat to allow for more detailed customization of web chat. These two objects are described below.

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.

ArgumentTypeDescription
classNameStringThe 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.

ArgumentTypeDescription
classNameStringThe 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.

ArgumentTypeDescription
valueStringThe 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).

ArgumentTypeDescription
isEnabledbooleanWith 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.

ArgumentTypeDescription
listenerFunctionThe 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.

ArgumentTypeDescription
listenerFunctionThe 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.writeableElements

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>';

Element nameDescription
headerBottomElementAdd 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.
welcomeNodeBeforeElementAdd content above the welcome node. Useful for further introductions of your assistant or disclaimers.
homeScreenHeaderBottomElementAdd content to the home screen below the header and above the rest of the homescreen content. Useful for replacing the avatar and/or welcome text with custom content. This could be a full width image of your avatar or if you want to replace the welcome message with text with some custom styling.
homeScreenAfterStartersElementAdd 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.
beforeInputElementAdd content that appears after the messages area when talking with the Assistant and before the input field.

Home Screen

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.

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',
      }
    ]
  }
});

ParameterTypeRequiredDescription
homeScreenConfigObjectRequiredThe configuration object for a home screen.
homeScreenConfig.is_onbooleanOptionalIf true, will show a home screen.
homeScreenConfig.greetingtextOptionalText to introduce your assistant.
homeScreenConfig.startersObjectOptionalConfiguration for the conversation starter buttons.
homeScreenConfig.starters.is_onbooleanOptionalIf true will show conversation starter buttons.
homeScreenConfig.starters.buttons[]Object[]OptionalAn array of conversation starter button configurations.
homeScreenConfig.starters.buttons[].labelstringOptionalThe 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_urlstringOptionalThe image url to load as the bot avatar in home screen.

Launcher

The web chat launcher welcomes and engages customers so they know where to find help if they need it. For more information about the default launcher behavior see, launcher appearance and behavior.

instance.updateLauncherAvatarURL()

updateLauncherAvatarURL() allows you modify the default web chat launcher avatar with a custom image. The avatar's 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 Watson 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()

ParameterTypeRequiredDescription
greetingMessageStringRequiredThe new greeting text for the launcher.
launcherTypeStringOptionalThere 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.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()

ParameterTypeRequiredDescription
timeNumberOptionalThe 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.
launcherTypeStringOptionalThere 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)

Security

Authenticate and authorize users of your web chat with your sites own methods and then pass user information into the web chat. Learn more

instance.updateIdentityToken()

The function takes a signed JWT identity token used to verify the data you send to Watson 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 service from webhooks. The data inside context.integrations.chat.private will not be returned when a message is received.

ParameterTypeRequiredDefault
identityTokenJWTRequired

instance.destroySession()

Web chat stores information about the current session in the browser. This method removes all cookie or browser storage related to the current web chat session. You can call this method as part of your logout sequence to avoid a subsequent users web chat trying to reconnect to the previous user's session. If you forget to call this, JWT protected information will not be at risk, but web chat will try to connect to the previous session and fail.

Example

instance.destroySession();

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.

Example

instance.updateUserID('some-user-id-that-is-not-identifiable');

Event Handling

Throughout its life cycle, web chat fires a variety of events your code can subscribe to. Using event handler callbacks, you can manipulate the contents of messages before they are sent or after they are received; you can change how your website is rendered when the web chat opens or closes; and you can even render your own custom response types inside the web chat widget. The follow methods allow you to manage your event subscriptions.

Learn more about events

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.

ParameterTypeRequiredDefaultDescription
optionsObjectRequiredMethod options.
options.typestringRequiredThe event to listen to (for example, * or send). For more information, see Events.
options.handlerfunctionRequiredThe callback that will handle the event.
Example

window.watsonAssistantChatOptions = {
  integrationID: 'YOUR_INTEGRATION_ID',
  region: 'YOUR_REGION',
  serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
  onLoad: function(instance) {
    // Your handler
    function handler(obj) {
      console.log(obj.type, obj.data);
    }
  
    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 }
    ]);
  
    // Render your web chat.
    instance.render();
  }
};

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.

ParameterTypeRequiredDefaultDescription
optionsObjectRequiredMethod options.
options.typestringRequiredThe event type you no longer want to listen for (for example, * or send). For more information, see Events.
options.handlerfunctionOptionalA 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

window.watsonAssistantChatOptions = {
  integrationID: 'YOUR_INTEGRATION_ID',
  region: 'YOUR_REGION',
  serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
  onLoad: function(instance) {
    // Your handler
    function handler(obj) {
      console.log(obj.type, obj.data);
    }
  
    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' });
  
    // Render your web chat.
    instance.render();
  }
};

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.

ParameterTypeRequiredDefaultDescription
optionsObjectRequiredMethod options.
options.typestringRequiredThe event type to listen for (for example, * or send). For more information, see Events.
options.handlerfunctionRequiredThe callback that will handle the event. See Events.
Example

window.watsonAssistantChatOptions = {
  integrationID: 'YOUR_INTEGRATION_ID',
  region: 'YOUR_REGION',
  serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
  onLoad: function(instance) {
    // Your handler
    function handler(obj) {
      console.log(obj.type, obj.data);
    }
  
    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 }
    ]);
  
    // Render your web chat.
    instance.render();
  }
};

Languages

Web chat has a set of hardcoded text strings that are used to display messages to users that do not come from your assistant. These include strings like the "Type something..." that appears as the placeholder text inside the message input field or the "Send one of these messages" that appears when you open the suggestions menu.

Web chat includes a set of out-of-the-box translations for these strings in the following languages:

  • Arabic (ar)
  • Chinese (zh)
  • Chinese/Taiwan (zh-tw)
  • Czech (cs)
  • Dutch (nl)
  • English (en)
  • French (fr)
  • German (de)
  • Italian (it)
  • Japanese (ja)
  • Korean (ko)
  • Portuguese/Brazil (pt-br)
  • Spanish (es)

You can switch web chat to use one of these languages by calling the updateLocale instance method and passing it the given language code.

In addition to switching to any of the supported languages, you can also provide your own strings to either change the string for any given message or to provide your own language support. For example, when you are prompting for the user's name, you might want to replace the default text "Type something..." with "Enter your name".

Replacement strings are specified in a JSON object. 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; you can find that list on the tags page. These files are in the ICU Message Format JSON representations of all of the languages that are supported by Watson Assistant action skills, dialog skills and the web chat widget. Web chat defaults to US English, but you can pass in an object containing language strings with the updateLanguagePack instance method.

Note: The provided JSON object does not need to contain all strings, just the strings you want to update. Your changes are merged with the existing language strings.

Locales

In addition to the languages listed above, web chat supports locales with a more specific region code (e.g. en-gb). The region goes beyond the language and controls other things such as the format of dates and times shown by web chat. For example, date strings in UK English are in dd/mm/yyyy format, while US English dates are in mm/dd/yyyy format.

Note: This setting does not affect any strings received from your action, dialog or search skill; it applies only to strings generated by web chat itself.

The locales supported by web chat are a superset of the languages supported by action and dialog skills. Web chat supports the locales that are provided by the dayjs library.

instance.updateLocale()

Changes the current language and locale in use by web chat. See Languages above. 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

onLoad: async (instance) => {
  // Web chat makes an asynchronous request to get other language data so you need to use async/await.
  await instance.updateLocale('fr');
  instance.render();
}

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.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.

Example

const customLanguagePack = {
  errors_communicating: 'Oops, something went wrong. Refresh to try again.'
};
instance.updateLanguagePack(customLanguagePack);

Session History

When session history is enabled web chat will continue to display the messages from the current session even after a page change/refresh. However when some messages are initially rendered they can be dependent on some state, perhaps a bank balance or whether its morning, afternoon, or evening. In order to correctly re-render these messages there needs to be a way to save the state and then access it again when the page changes/refreshes. That's where instance.updateHistoryUserDefined() comes in.

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.

ParameterTypeDescription
messageIDStringThe 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 customResponse the id can be found at event.data.fullMessage.id.
dataAnythingThe 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 customResponse section.

Custom Panels

The web chat has a custom panels object that provides a getPanel() method that returns a custom panel instance.

A custom panel instance comes with methods to display your panel with some basic configuration options and close it. It also provides the host element that can display your custom content in the panel.

instance.customPanels

Returns an object that can be used to control custom panels.

MethodDescription
instance.customPanels.getPanel()Returns a custom panel instance.

Custom Panel Instance

The following is the list of all the available custom panel instance methods.

MethodDescription
openOpens the custom panel with basic config options that change the look and feel of the panel.
closeCloses the custom panel if it is open.

The following is the list of all the available custom panel instance properties.

PropertyDescription
hostElementReturns 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:

ParameterTypeDefaultDescription
disableAnimationbooleanfalseDisables the panel's opening/closing animations.
disableDefaultCloseActionbooleanfalseDisables 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.
hideBackButtonbooleanfalseIndicates 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.
hideCloseAndRestartButtonbooleanfalseIndicates 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.
hideCloseButtonbooleanfalseIndicates 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.
hidePanelHeaderbooleanfalseIndicates if the entire panel header should be hidden.
onClickBackfunctionThis callback is called when the back button is clicked.
onClickClosefunctionThis callback is called when the close button is clicked. This is called even if disableDefaultCloseAction is set to true.
onClickCloseAndRestartfunctionThis 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.
titlestringThe 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>';

Tours
Beta

The web chat instance has a tours object that contains methods which can be used to manipulate the tour view.

Tour Methods

The following is the list of all the available instance methods for tours.

MethodDescription
startTourSends a message request then switch to the tour view after receiving the new tour data from the request.
endTourClears all tour data, closes the tour, and switches to the launcher.
goToNextStepMove forward one step in the tour.
goToStepMove to the step within the tour that has a matching step_id.

tours.startTour()
Beta

This method accepts a message string that will be sent to the backend 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');

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.

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.

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');

Miscellaneous

Other useful methods for a web chat instance.

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.

ParameterTypeRequiredDefaultDescription
messageObject or StringRequiredA 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.)
optionsObjectMethod options.
options.silentBooleanWhether 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.skipPauseBooleanIndicates 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
instance.send('get a human agent').catch((error) => {
  console.error('This message did not send!');
});


const sendObject = {
  input: {
    message_type: 'text',
    text: 'get human agent'
  }
};
const sendOptions = {
  silent: true
}
instance.send(sendObject, sendOptions).catch((error) => {
  console.error('This message did not send!');
});

instance.getState()

Returns properties representing the current state of the web chat.

ParameterTypeDescription
isAssistantInputFieldVisibleBooleanIs the input field visible if user is talking to assistant.
isConnectedWithHumanAgentBooleanIs the web chat currently connected with a human agent.
isConnectingWithHumanAgentBooleanIndicates if web chat has requested to be connected to a human agent but an agent has not yet joined the conversation.
isDebugEnabledBooleanIndicates if the debug flag for web chat was set to true.
isHomeScreenOpenBooleanIs the home screen open.
isTourActive
Beta
BooleanIs 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.
isWebChatOpenBooleanIs the web chat currently in an open state.
hasUserSentMessageBooleanHas the user sent a message.
sessionIDStringThe active Watson Assistant sessionID.
viewStateObjectThe 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.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.updateIsTypingCounter()

Changes the internal counter that determines whether the "is typing" indicator is shown. This indicator is an animated "..." that let's 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.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.

ParameterTypeRequiredDescription
isVisiblebooleanRequiredA 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.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.

ParameterTypeRequiredDescription
optionsarrayRequiredAn 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].textstringRequiredThe text to display for this option.
options[n].handlerfunctionRequiredA 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`) },
]);

Human Agent

Methods for dealing with human agents.

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.isConnectedWithHumanAgent || state.isConnectingWithHumanAgent) {
  await instance.agentEndConversation();
}