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 loadWatsonAssistantChat() 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 methods are broken up into the following sections: Chat Window,Home Screen, Security, Theming, Events, Languages, CustomPanels, 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.
closeWindowCloses the chat window if it is currently open.
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.
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.
openWindowOpens the chat window if it is currently closed.
renderRenders the web chat widget on your page.
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.
toggleOpenToggles the current open or closed state of the window.
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.
updateLanguagePackUpdates the language pack used for displaying message strings.
updateLauncherGreetingMessageSets the greeting message for the launcher.
updateLocaleChanges the current locale in use by the widget.
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.
writeableElementsA list of container elements where custom elements can be attached.

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

ParameterTypeDefaultDescription
BASE-z-indexNumber99999The z-index on your website that the web chat is assigned to.
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-heightCSS height value640pxThe default value the web chat will set its height to. Web chat has a max-height of 640px and can't be greater than that. 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 height.

Customizable font 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.
HOME_SCREEN-greeting-font-familyString'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serifThe font family used by main greeting message on the home screen.

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.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.
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.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. 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.global.system.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 (for example, "We are having some issues right now. Please refresh to try again").

You can replace these text strings to use a language other than English, or to customize the messages for branding or style. For example, when you are prompting for the user's name, you might want to replace the default text "Enter a message" with "Enter your name".

Replacement strings are specified in a JSON object. The languages folder contains the files web chat uses when displaying translatable strings. 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 language strings, web chat supports a more specific locale setting. The locale goes beyond language strings, and also controls 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:

    • ar
    • ar-dz
    • ar-kw
    • ar-ly
    • ar-ma
    • ar-sa
    • ar-tn
    • cs
    • de
    • de-at
    • de-ch
    • en
    • en-sg
    • en-au
    • en-ca
    • en-gb
    • en-ie
    • en-il
    • en-nz
    • es
    • es-do
    • es-us
    • fr
    • fr-ca
    • fr-ch
    • it
    • it-ch
    • ja
    • ko
    • pt
    • pt-br
    • zh
    • zh-cn
    • zh-tw

instance.updateLocale()

Changes the current locale in use by the widget. See Languages for the available locales. 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 is 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.

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 users 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 or at this tutorial.

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

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
messageObjectRequiredA v2 message request object. (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 2 seconds 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.
Example

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

instance.getState()

Returns properties representing the current state of the web chat.

ParameterTypeDescription
isWebChatOpenBooleanIs the web chat currently in an open state.
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.
isHomeScreenOpenBooleanIs the home screen open.
isAssistantInputFieldVisibleBooleanIs the input field visible if user is talking to assistant.
hasUserSentMessageBooleanHas the user sent a message.
sessionIDStringThe active Watson Assistant sessionID.
Example

instance.getState();

instance.getWidgetVersion()

Returns the version number of the widget code.

Example

instance.getWidgetVersion();

instance.updateCustomMenuOptions()

Updates the display of custom menu options that appear in the header. To the right of the title in the header, an overflow menu may appear that contains additional options. This function may be used to add or update custom options in that menu that will call a click listener when clicked. At the moment these options can appear in the main chat window with the bot or in the window when chatting with an agent.

ParameterTypeRequiredDescription
typestringRequiredThe type/location of the menu to update. The current valid values are "bot" and "agent"
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('bot', [
  { 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();
}