### Install Watson Assistant Web Chat using Script Tag
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-overview
This method installs the Watson Assistant web chat using a script tag, making it framework-agnostic. It dynamically loads the chat script from a CDN and requires integrationID, region, and serviceInstanceID for initialization. The onLoad callback is used to render the widget.
```html
```
--------------------------------
### Start a new tour
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Initiates a new tour by sending a message string to the backend. Once the tour data is received, the tour view updates, and the `tour:start` event fires.
```javascript
// Send a message that corresponds to a "welcome tour" action and returns to show the tour data.
instance.tours.startTour('welcome tour');
```
--------------------------------
### Tour Management Methods (Beta)
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Methods for managing user tours, including ending, navigating steps, and starting tours.
```APIDOC
## Tour Management Methods (Beta)
### Description
These methods allow for the management of user tours within the chat interface. They enable ending a tour, navigating to specific steps, and initiating new tours.
### Method
Instance Methods
### Endpoint
N/A (Methods of `instance.tours`)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### `instance.tours.endTour()`
##### Description
Clears all tour data, closes the tour, and switches to the launcher. When the user clicks the launcher, the main chat window opens. The user can start the tour again with the tour card from the chat window.
#### `instance.tours.goToNextStep()`
##### Description
Moves to the next step in the tour. When the next step is switched to, the `tour:step` event fires.
#### `instance.tours.goToStep(stepId)`
##### Parameters
- **stepId** (String) - Required - The ID of the step to navigate to.
##### Example
```javascript
// 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(message)`
##### Parameters
- **message** (String) - Required - A message string that sends data to the back end to get a new tour. Once the tour data returns, the tour view switches automatically. When the tour switches, the `tour:start` event fires.
##### Example
```javascript
// Send a message that corresponds to a "welcome tour" action and returns to show the tour data.
instance.tours.startTour('welcome tour');
```
### Response
#### Success Response
N/A (These methods typically do not return values but trigger UI changes or events.)
#### Response Example
N/A
```
--------------------------------
### Initialize Web Chat with Customizations
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
An example demonstrating how to initialize the web chat, set a default message input value, add a keydown listener to the raw HTML element, and set up a change listener for the input field, all after the 'chat:ready' event.
```javascript
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));
}});
```
--------------------------------
### Set Custom Attributes Before Chat - Genesys SDK
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-genesys
This example demonstrates how to set custom attributes using the Genesys SDK before a chat starts. It utilizes the `agent:pre:startChat` event to populate the `preStartChatPayload.customAttributes` property with key-value pairs.
```javascript
instance.on({
type: 'agent:pre:startChat',
handler: (event) => {
event.preStartChatPayload = {
customAttributes: {
attribute1: 'Some value',
},
};
},
});
```
--------------------------------
### agent:pre:startSessionHistory Handler Example
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-events
An example handler function that processes messages for session history, censoring specific words and hiding entire messages if a certain phrase is detected.
```APIDOC
## agent:pre:startSessionHistory Handler Example
### Description
This handler processes messages between the user and an agent to modify them before they are added to the session history. It replaces occurrences of the word "secret" (case insensitive) with "******" and hides the entire message if it contains the phrase "hide this message".
### Method
Event Handler (for `agent:pre:startSessionHistory`)
### Endpoint
N/A (Event-driven)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
**event** (`Object`) - The event object containing message data.
- **message** (`Object`) - Contains input from the user or output from the agent.
- **output** (`Object`) - Contains the agent's response.
- **generic** (`Array`) - An array of message objects, typically containing text.
- **input** (`Object`) - Contains the user's input.
- **text** (`String`) - The text content of the user's message.
**instance** (`Object`) - The current instance of the web chat (used for event registration).
### Request Example
```javascript
// Assuming 'instance' is an initialized Web Chat instance
async function agentPreSessionHistoryHandler(event) {
let hideWholeMessage = false;
if (event.message.output) {
// This is a message from an agent.
event.message.output.generic.forEach(item => {
// This code is only handling text messages. If the service desk can produce other types of message responses,
// (such as image responses), you need to add additional code for each of those possible types.
if (item.text) {
item.text = item.text.replace(/secret/gi, '******');
if (item.text.toLowerCase().includes('hide this message')) {
hideWholeMessage = true;
}
}
});
} else if (event.message.input) {
// This is a message from a user.
event.message.input.text = event.message.input.text.replace(/secret/gi, '******');
if (event.message.input.text.toLowerCase().includes('hide this message')) {
hideWholeMessage = true;
}
}
if (hideWholeMessage) {
event.message = null; // Hides the entire message from history
}
}
instance.on({ type: 'agent:pre:startSessionHistory', handler: agentPreSessionHistoryHandler });
```
### Response
#### Success Response (Event Handled)
- The `event.message` object is modified in place. If `hideWholeMessage` is true, `event.message` is set to `null`.
#### Response Example
(See Request Example for logic. The actual session history modification depends on the web chat's internal handling after this event resolves.)
```
--------------------------------
### Initialize Web Chat and Get Instance using onLoad
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
This script initializes the IBM watsonx Assistant web chat with specified configuration options. The `onLoad` callback function receives the initialized chat instance, which can then be used to call runtime utility methods like `render()`. It also demonstrates how to assign the instance to a global variable for broader access.
```javascript
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
onLoad: async (instance) => {
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);
});
```
--------------------------------
### Set Customer Name and Custom Fields for Nice CXone in Web Chat
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-nice
This code example demonstrates how to use the `agent:pre:startChat` event in IBM watsonx Assistant web chat to provide customer details to Nice CXone before a chat begins. It shows how to set the `customerName` and populate the `customFields` for the consumer contact.
```javascript
instance.on('agent:pre:startChat', (preStartChatPayload) => {
// Set the customer name.
preStartChatPayload.customerName = 'Customer Name';
// Set custom fields.
preStartChatPayload.consumerContact.customFields = {
// Add your custom fields here.
};
});
```
--------------------------------
### Apply Carbon Theme to Web Chat
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-overview
Customize the web chat's visual theme by applying one of the predefined Carbon themes. Options include 'white', 'gray-10', 'gray-90', and 'gray-100', influencing the overall color scheme.
```javascript
const options = {
// ... other options
customizations: {
carbonTheme: 'gray-90' // Example: Use a dark theme
}
};
window.loadChat(options);
```
--------------------------------
### tour:start Event
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-events
This event triggers when a tour begins, initiated by a tour message with skip_card: true, a call to the startTour instance method, or the user clicking the 'start tour' card. It does not fire when the user clicks the restart button.
```APIDOC
## tour:start
### Description
This event fires when a tour starts. The tour starts when the web chat receives a tour message with `skip_card: true`, when you use the instance method startTour, or when the user clicks the start tour card. This event does not fire when the user clicks the restart button.
### Method
Event
### Endpoint
N/A (Event Listener)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Event Payload
- **event** (`Object`) - The event object.
- **event.type** (`String`) - The event type ('tour:start').
- **event.reason** (`string`) - The reason the tour starts. Possible values include 'start_tour_method', 'skip_card', 'start_tour_clicked'.
- **instance** (`Object`) - The current instance of the web chat.
### Response Example
```json
{
"event": {
"type": "tour:start",
"reason": "start_tour_method"
},
"instance": {
"webchat_instance_details": "..."
}
}
```
```
--------------------------------
### Sending Messages
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Examples of sending text messages, messages with options like silent mode, and messages that set context variables.
```APIDOC
## Sending Messages
### Description
Examples of sending text messages, messages with options like silent mode, and messages that set context variables.
### Method
POST (implicitly)
### Endpoint
N/A (Method of an instance)
### Parameters
#### Request Body
- **input** (Object) - Required - The message input object.
- **message_type** (String) - Required - The type of message, e.g., 'text'.
- **text** (String) - Required - The content of the message.
- **options** (Object) - Optional - Options for sending the message.
- **silent** (Boolean) - Optional - If true, the message request is not visible to the user.
- **context** (Object) - Optional - Context for the message.
- **skills** (Object) - Optional - Skills-related context.
- **[skill_name]** (Object) - Required - Skill object.
- **user_defined** (Object) - Optional - User-defined variables for the skill.
- **[variable_name]** (any) - Description
### Request Example
```javascript
// Simple text message
instance.send('get a human agent');
// Message with silent option
const sendObject = {
input: {
message_type: 'text',
text: 'get a human agent'
}
};
const sendOptions = {
silent: true
}
instance.send(sendObject, sendOptions).catch(console.error);
// Message setting a context variable
const sendObjectWithContext = {
input: {
message_type: 'text',
text: 'get a human agent'
},
context: {
skills: {
['main skill']: {
user_defined: {
custom_var: 'My custom variable',
}
}
}
}
};
instance.send(sendObjectWithContext);
```
### Response
#### Success Response (Promise Resolved)
- The promise resolves when the message is sent successfully.
#### Response Example
N/A (Promise-based)
```
--------------------------------
### Control Chat Loading Indicator with instance.updateIsChatLoadingCounter()
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Manages the visibility of the full-screen loading indicator by updating an internal counter. The indicator is shown when the counter is greater than zero. Use 'increase' to show and 'decrease' to hide. Ensure a decrease follows every increase to prevent the indicator from getting stuck.
```javascript
instance.updateIsChatLoadingCounter('increase'); // Show the indicator.
instance.updateIsChatLoadingCounter('decrease'); // Hide the indicator.
```
--------------------------------
### Update CSS Variables for Theming
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-overview
Fine-tune the web chat's appearance by directly manipulating CSS variables. This allows for granular control over colors and fonts, enabling advanced theming beyond predefined themes. Accessible via instance method.
```javascript
const options = {
// ... other options
customizations: {
updateCSSVariables: {
'--primary-color': '#0000ff',
'--font-family': 'Arial, sans-serif'
}
}
};
window.loadChat(options);
```
--------------------------------
### instance.showLauncherGreetingMessage()
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Controls the timing of the greeting message appearance. Allows setting specific times for desktop and mobile launchers.
```APIDOC
## instance.showLauncherGreetingMessage()
### Description
This method controls the timing of when the greeting message appears. The default behavior is that the greeting message appears after 15 seconds. If the greeting message is already visible, then it ignores any new set times. If the greeting message is visible to the user when the page changes or reloads, the greeting message remains visible when reloading. The updated timing does not save in the session storage; if the user changes pages or reloads the page before the greeting message appears, 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().
### Method
Instance Method
### Endpoint
N/A (Method of an instance)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Method Parameters
- **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 appears immediately.
- **launcherType** (String) - Optional - There are two different launchers that appear depending on the end user's 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 sets for both.
### Request Example
```javascript
// To show the desktop launcher in 4s (the mobile launcher shows 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);
```
### Response
#### Success Response
N/A (This method does not return a value but modifies the launcher's behavior.)
#### Response Example
N/A
```
--------------------------------
### Update Web Chat Locale
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-overview
Switch the display language for static text within the web chat. This method uses ISO language codes. It is independent of the assistant's language setting and affects only web chat UI elements, not content from skills.
```javascript
const options = {
// ... other options
customizations: {
updateLocale: 'es' // Spanish
}
};
window.loadChat(options);
```
--------------------------------
### Update Web Chat Language Pack
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-overview
Modify static text displayed in the web chat or provide custom translations. This method merges your provided strings with existing language packs. The JSON object should contain only the strings you wish to update. Accessible via instance method.
```javascript
const options = {
// ... other options
customizations: {
updateLanguagePack: {
"common.welcome": "Hello! How can I help you today?",
"common.type_something": "Enter your name"
}
}
};
window.loadChat(options);
```
--------------------------------
### Update Launcher Configuration
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Manages the launcher feature of the web chat, allowing control over its visibility, call-to-action elements, and related configurations.
```APIDOC
## POST /websites/web-chat_global_assistant_watson_cloud_ibm_docs/updateLauncherConfig
### Description
Manages the launcher feature of the web chat. You can control if the launcher shows, if it shows a call to action, and configuration around those features.
### Method
POST
### Endpoint
/websites/web-chat_global_assistant_watson_cloud_ibm_docs/updateLauncherConfig
### Parameters
#### Request Body
- **launcherConfig** (Object) - Required - Configuration object for the chat launcher.
- **launcherConfig.is_on** (boolean) - Optional - Enables or disables the chat launcher.
- **launcherConfig.show_cta** (boolean) - Optional - Determines whether to display a call to action on the launcher.
- **launcherConfig.cta_text** (string) - Optional - The text to display for the call to action.
- **launcherConfig.cta_url** (string) - Optional - The URL to navigate to when the call to action is clicked.
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### instance.updateHomeScreenConfig
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Dynamically updates the web chat home screen configuration, including enabling/disabling the feature, changing conversation starters, welcome text, and background gradients.
```APIDOC
## instance.updateHomeScreenConfig
### Description
This method turns the home screen feature on and off, and dynamically updates the home screen content. It applies when you want to have different conversation starters or welcome text on different pages of your website. You can also control the home screen background.
### Method
`POST` (Inferred - typically methods modifying state are POST or PUT, but this is a JS API call, so not strictly HTTP)
### Endpoint
`instance.updateHomeScreenConfig()`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **homeScreenConfig** (Object) - Required - An object containing the home screen configuration.
- **background_gradient** (Object) - Optional - Configuration for the background gradient.
- **type** (String) - Optional - Specifies the type of gradient ('top_corner_out' or 'bottom_up').
- **enabled** (Boolean) - Optional - Whether to enable the background gradient.
- **conversation_starters** (Array) - Optional - An array of objects defining conversation starter buttons.
- **welcome_text** (String) - Optional - The welcome text displayed on the home screen.
### Request Example
```javascript
// Example: Enabling a bottom-up gradient and setting welcome text
instance.updateHomeScreenConfig({
homeScreenConfig: {
background_gradient: {
type: 'bottom_up',
enabled: true
},
welcome_text: 'Welcome! How can I help you today?'
}
});
// Example: Disabling the home screen
instance.updateHomeScreenConfig({
homeScreenConfig: {
enabled: false
}
});
```
### Response
#### Success Response (200)
(No specific success response body defined, operation is generally asynchronous)
#### Response Example
None provided.
```
--------------------------------
### Inject HTML into welcomeNodeBeforeElement using JavaScript
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
This snippet demonstrates how to inject custom HTML, including a disclaimer, into the `welcomeNodeBeforeElement` of the web chat. This allows for pre-introduction content. Styling for injected elements should be handled by scoping CSS within `#WACContainer.WACContainer` or using ShadowRoot.
```javascript
instance.writeableElements.welcomeNodeBeforeElement.innerHTML = '
Disclaimer text...
';
```
--------------------------------
### Update Web Chat Launcher Configuration
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Configure the web chat launcher's appearance and behavior, including options for desktop and mobile devices. This method allows toggling the launcher on/off and customizing call-to-action pop-ups with titles and display times.
```javascript
instance.updateLauncherConfig({
is_on: false, // turn off the launcher
});
```
```javascript
instance.updateLauncherConfig({
is_on: true, // turn on the launcher
desktop: {
is_on: true, // turn on the call to action pop up on desktop devices
title: 'Click me now!', // update the text displayed in the call to action
time_to_expand: 10, // amount of time, in seconds, before the call to action is displayed
},
mobile: {
is_on: false // turn off the call to action pop up on mobile devices
},
});
```
--------------------------------
### agent:pre:startChat Event
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-events
This event fires before a chat with a service desk starts, allowing you to gather information or cancel the chat before connecting to the service desk.
```APIDOC
## agent:pre:startChat Event
### Description
This event fires before a chat with a service desk starts. It occurs when the user clicks the "Request agent" button and before any attempt is made to communicate with the service desk. Use the event to gather information before you connect to the service desk. A custom panel can display to the user to collect this information. The service desk does not connect until all the event's handlers resolve. You can use this event to cancel the chat.
### Method
Event Listener (No specific HTTP method associated, handled internally by the web chat)
### Endpoint
Not Applicable (Internal event)
### Parameters
#### Event Parameters
- **event** (Object) - The event object.
- **event.type** (String) - The event type (`agent:pre:startChat`).
- **event.message** (Object) - The full v2 message API Response object that passes to the service desk.
- **event.cancelStartChat** (boolean) - Assignable. Set to `true` to cancel the chat process.
- **event.sessionHistoryKey** (String) - The session history key that loads an agent app version of the web chat.
- **event.preStartChatPayload** (any) - Assignable. The payload of data that passes to the service desk when a chat starts.
- **instance** (Object) - The current instance of the web chat.
### Request Example
```javascript
let preStartChatResolve;
let preStartChatEvent;
function preStartChatHandler(event, instance) {
// This Promise causes the "agent:pre:startChat" event to pause until the custom panel is closed.
// There is a click listener in the custom panel that resolves it.
return new Promise((resolve) => {
preStartChatResolve = resolve;
preStartChatEvent = event;
instance.customPanels.getPanel().open({ 'title': 'Connect to agent', hideCloseButton: true });
});
}
function createCustomPanel(panel) {
const container = document.createElement('div');
container.innerText = 'To get an agent, click this button:';
const button = document.createElement('button');
button.type = 'button';
button.innerText = 'Agent!';
button.addEventListener('click', () => {
// Once the user has clicked the button, close the panel, set a payload that can be made available to the service
// desk and the resolve the promise that our handler is waiting on to continue the connect to agent. What is passed
// here depends on the service desk (which cannot support this property).
preStartChatEvent.preStartChatPayload = { someData: 'Depends on the service desk' };
panel.close();
preStartChatResolve();
});
container.appendChild(button);
panel.hostElement.appendChild(container);
}
instance.on({ type: 'agent:pre:startChat', handler: preStartChatHandler });
createCustomPanel(instance.customPanels.getPanel());
```
### Response
(No direct response, event handlers modify the chat process or parameters)
```
--------------------------------
### Update Launcher Configuration
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Updates the configuration of the web chat launcher, controlling its visibility, behavior, and call-to-action elements on desktop and mobile devices.
```APIDOC
## Update Launcher Configuration
### Description
Updates the web chat launcher's configuration. This allows control over whether the launcher is active, and how it behaves on desktop and mobile devices, including display of call-to-action elements.
### Method
`updateLauncherConfig(config: object)`
### Parameters
#### Request Body
- **launcherConfig.is_on** (Boolean) - Optional - Default: `true` - If `false`, the website code must call `instance.openWindow()` to open the chat window. Alternatively, use `openChatByDefault` and `hideCloseButton`.
- **launcherConfig.mobile** (Object) - Optional
- **launcherConfig.mobile.is_on** (Boolean) - Optional - Default: `true` - Determines if the launcher expands with a call to action on mobile.
- **launcherConfig.mobile.title** (String) - Optional - The title text for the expanded launcher on mobile. Defaults to a translated string if not provided.
- **launcherConfig.mobile.avatar_url_override** (String) - Optional - A URL for a custom avatar image for the mobile launcher. Ignored when AI theme is on.
- **launcherConfig.mobile.time_to_expand** (Number) - Optional - Time in seconds before the mobile launcher expands. Defaults to 15 seconds.
- **launcherConfig.desktop** (Object) - Optional - Configuration for the launcher call to action on desktop devices.
- **launcherConfig.desktop.is_on** (Boolean) - Optional - Default: `true` - Determines if the launcher expands with a call to action on desktop.
- **launcherConfig.desktop.title** (String) - Optional - The title text for the expanded launcher on desktop. Defaults to a translated string if not provided.
- **launcherConfig.desktop.avatar_url_override** (String) - Optional - A URL for a custom avatar image for the desktop launcher. Ignored when AI theme is on.
- **launcherConfig.desktop.time_to_expand** (Number) - Optional - Time in seconds before the desktop launcher expands. Defaults to 15 seconds.
### Request Example
```json
{
"launcherConfig": {
"is_on": false,
"desktop": {
"is_on": true,
"title": "Click me now!",
"time_to_expand": 10
},
"mobile": {
"is_on": false
}
}
}
```
### Response
#### Success Response (200)
Indicates the launcher configuration was updated successfully. Response body is typically empty or a success confirmation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Get Widget Version with instance.getWidgetVersion()
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
The `instance.getWidgetVersion()` method returns the version number of the web chat widget's code. This is useful for tracking which version of the widget is currently deployed.
```javascript
instance.getWidgetVersion();
```
--------------------------------
### Configure Nice CXone DFO Integration for Web Chat
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-nice
This configuration enables the integration between IBM watsonx Assistant web chat and Nice CXone DFO Live Chat. It requires specifying the DFO environment, channel ID, and brand ID. The `onLoad` function ensures the chat instance is rendered after configuration.
```javascript
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
serviceDesk: {
// This enables the DFO integration.
integrationType: 'nicedfo',
niceDFO: {
environment: 'NA1',
channelID: 'YOUR_CHANNEL_ID',
brandID: 1234, // Note that this is a number and not a string.
},
},
onLoad: async (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);});
```
--------------------------------
### Launcher Customizable Variables
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Override pre-configured color variables for the web chat launcher and desktop launcher expanded message to customize their appearance.
```APIDOC
## Customizable Launcher Variables
You can override the pre-configured color variables for the web chat launcher and desktop launcher expanded message.
### Parameters
#### Query Parameters
- **LAUNCHER-color-avatar** (`Hex color code`) - Description: The color of the default launcher avatar.
- **LAUNCHER-color-background** (`Hex color code`) - Description: The background color of the default launcher.
- **LAUNCHER-color-background-active** (`Hex color code`) - Description: The background color of the default launcher in the active state.
- **LAUNCHER-color-background-hover** (`Hex color code`) - Description: The background color of the default launcher in the hover state.
- **LAUNCHER-color-focus-border** (`Hex color code`) - Description: The border color of the launcher in the focus state.
- **LAUNCHER-EXPANDED-MESSAGE-color-background** (`Hex color code`) - Description: The background color of the desktop launcher expanded message.
- **LAUNCHER-EXPANDED-MESSAGE-color-background-active** (`Hex color code`) - Description: The background color of the desktop launcher expanded message in the active state.
- **LAUNCHER-EXPANDED-MESSAGE-color-background-hover** (`Hex color code`) - Description: The background color of the desktop launcher expanded message in the hover state.
- **LAUNCHER-EXPANDED-MESSAGE-color-text** (`Hex color code`) - Description: The text color of the desktop launcher expanded message.
- **LAUNCHER-EXPANDED-MESSAGE-color-focus-border** (`Hex color code`) - Description: The border color of the desktop launcher expanded message in the focus state.
- **LAUNCHER-MOBILE-color-text** (`Hex color code`) - Description: The text color of the mobile launcher message.
### Request Example
```javascript
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();
```
```
--------------------------------
### Screen Sharing Integration
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-custom-sd
Enables integration with service desk provided screen sharing or co-browsing capabilities. It allows requesting user permission to start screen sharing and stopping it.
```APIDOC
## Screen Sharing
### Description
Integrate screen sharing or co-browsing capabilities provided by your service desk. The web chat facilitates requesting user approval for screen sharing and allows the user to stop the session. The web chat itself does not provide screen sharing functionality; it acts as an intermediary for permission requests.
### Functions
#### `callback.screenShareRequest()`
* **Description**: Initiates a screen sharing request to the user. A modal will appear asking the user for approval. This function returns a Promise that resolves with the user's response (approve/deny).
* **Returns**: `Promise` - Resolves to true if the user approves, false otherwise.
#### `callback.screenShareStop()`
* **Description**: Stops the screen sharing session. This can be called at any time, including while waiting for user approval, to implement timeouts or user-initiated cancellations.
### User-Initiated Stop
* **Description**: If the user stops screen sharing, the web chat will call the `screenShareStop` function on your integration.
```
--------------------------------
### Get Home Screen Input Element
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Provides access to the input field specifically located on the web chat's home screen. This function returns an object with the same methods as `getMessageInput`, allowing for similar interactions.
```javascript
instance.elements.getHomeScreenInput()
```
--------------------------------
### Configure Web Chat Home Screen
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Updates the home screen configuration for the web chat assistant. This includes enabling/disabling the screen, setting greeting messages, configuring starter buttons, and defining background gradients. It accepts a nested object with various boolean and string parameters.
```javascript
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'
}
});
```
--------------------------------
### Web Chat Configuration with Link IDs
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-configuration
This section details how to use the `pageLinkConfig` property to define custom link IDs that trigger specific text responses from the web chat. It also provides an example of the embed script configuration.
```APIDOC
## Web Chat Configuration with Link IDs
### Description
Configure the web chat to recognize specific URL parameters (`wa_lid`) and respond with predefined text using the `pageLinkConfig` embed script property. This allows for customized user interactions based on the link they use to access your website.
### Method
Embed Script Configuration
### Endpoint
N/A
### Parameters
#### Query Parameters
- **wa_lid** (String) - Optional - A unique identifier appended to website links to trigger specific web chat responses.
#### Request Body
```javascript
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
pageLinkConfig: {
linkIDs: {
'[id]': {
text: '[String]'
}
}
},
onLoad: async (instance) => {
await instance.render();
}
};
```
- **pageLinkConfig.linkIDs** (Object) - Required - Defines all recognized link IDs.
- **pageLinkConfig.linkIDs[id]** (Object) - Required - Represents how the web chat responds to a specific ID.
- **pageLinkConfig.linkIDs[id].text** (String) - Required - The text the assistant receives when the ID is recognized.
### Request Example
```javascript
```
### Response
#### Success Response (N/A)
N/A
#### Response Example
N/A
```
--------------------------------
### Migrate openWindow to changeView in JavaScript
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-events
This code demonstrates the migration from the deprecated 'openWindow' method to the 'changeView' method. It shows how to replace a direct call to open the main window with the equivalent 'changeView' call.
```javascript
// Old code.
instance.openWindow();
// New code.
instance.changeView('mainWindow');
```
--------------------------------
### Pass Salesforce Pre-chat Details via Context
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-salesforce
This JSON example shows how to configure Salesforce pre-chat details within the watsonx Assistant's context object. It illustrates setting `integrations.salesforce.pre_chat.details` and `integrations.salesforce.pre_chat.entities` which are used when a chat is initiated.
```json
{
"output": {
"generic": [
{
"response_type": "connect_to_agent",
"transfer_info": {
"target": {}
},
"agent_available": {
"message": "Yes! We\'re ready to help. Just ask."
},
"agent_unavailable": {
"message": "Sorry! We\'re not available."
},
"message_to_human_agent": "Help this super-customer!"
}
]
},
"context": {
"integrations": {
"salesforce": {
"pre_chat": {
"details": [
{
"label": "name",
"value": "Customer Name",
"transcriptFields": ["name__c"],
"displayToAgent": true
}
],
"entities": [
{
"entityName": "LiveChatTranscript",
"showOnCreate": "",
"linkToEntityName": "Case",
"linkToEntityField": "CaseId",
"saveToTranscript": "CaseId",
"entityFieldsMaps": [
{
"fieldName": "name__c",
"label": "name"
}
]
}
]
}
}
}
}
}
```
--------------------------------
### Control launcher greeting message display time
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Controls the timing of the launcher greeting message. It accepts milliseconds for delay and can specify 'mobile' or 'desktop' launchers. If no time is provided, it appears immediately. Existing timers are cleared when a new time is set.
```javascript
// To show the desktop launcher in 4s (the mobile launcher shows 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)
```
--------------------------------
### Configure Service Desk Integration for Web Chat
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-configuration
This example shows how to configure service desk integration options for the Watson Assistant web chat. It includes parameters like `serviceDesk.agentJoinTimeoutSeconds`, `serviceDesk.availabilityTimeoutSeconds`, `serviceDesk.disableAgentSessionHistory`, and `serviceDesk.skipConnectAgentCard` to control agent interaction behavior.
```javascript
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
serviceInstanceID: 'YOUR_SERVICE_INSTANCE_ID',
serviceDesk: {
skipConnectAgentCard: true,
},
onLoad: async (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);});
```
--------------------------------
### Navigate to a specific tour step
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
Navigates the tour to a specified step identified by its `stepId`. The `tour:step` event fires when the step is switched.
```javascript
// Switch to the step in the tour that is labeled as step_id: "welcome_3" in the tour json.
instance.tours.goToStep('welcome_3');
```
--------------------------------
### Get Internationalization Object using instance.getIntl()
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
This method returns the internationalization object used by the web chat for formatting translated strings, provided by the Format.JS library. A new IntlShape object is generated whenever the locale or language pack is updated.
```javascript
const placeholderText = instance.getIntl().formatMessage({ id: 'input_placeholder' });
```
--------------------------------
### Update Home Screen Configuration
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=api-instance-methods
This endpoint allows you to update the configuration of the web chat's home screen, including greetings, starter buttons, avatars, and background styles.
```APIDOC
## POST /websites/web-chat_global_assistant_watson_cloud_ibm_docs/updateHomeScreenConfig
### Description
Updates the configuration for the web chat's home screen.
### Method
POST
### Endpoint
/websites/web-chat_global_assistant_watson_cloud_ibm_docs/updateHomeScreenConfig
### Parameters
#### Request Body
- **homeScreenConfig** (Object) - Required - Defines the configuration object for a home screen.
- **homeScreenConfig.is_on** (boolean) - Optional - Shows a home screen when set to `true`.
- **homeScreenConfig.greeting** (text) - Optional - Provides text to introduce your assistant.
- **homeScreenConfig.starters** (Object) - Optional - Configures the conversation starter buttons.
- **homeScreenConfig.starters.is_on** (boolean) - Optional - Shows the conversation starter buttons when set to true.
- **homeScreenConfig.starters.buttons[]** (Object[]) - Optional - Contains an array of conversation starter button configurations.
- **homeScreenConfig.starters.buttons[].label** (string) - Optional - Displays text to the user in the button. It sends this text to your assistant when the user presses the button.
- **homeScreenConfig.bot_avatar_url** (string) - Optional - Loads the image url as the bot avatar on home screen.
- **homeScreenConfig.custom_content_only** (boolean) - Optional - Hides the avatar, greeting message, and starters so you can provide you own custom home screen.
- **homeScreenConfig.allow_return** (boolean) - Optional - Defaults to true. If true, a user will be able to navigate back to the home screen via navigation. If false, this home screen is treated like a "splash screen" and navigation back will not be possible.
- **homeScreenConfig.background** ('none', 'solid', 'top_corner_out', 'bottom_up') - Optional - Configures the background. 'none' keeps 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 the selected gradient option. If you have the AI theme enabled, this setting is ignored.
- **homeScreenConfig.background_gradient** (Object) - Deprecated - Configures the background gradient. This is deprecated. Use `background` instead. If you have the AI theme enabled, this setting is ignored.
- **homeScreenConfig.background_gradient.is_on** (boolean) - Optional - Adds a background gradient to the home screen if set to `true`. If `gradient_direction` is not specified then the gradient comes from the top corner out by default. This is deprecated. Use `background` instead.
- **homeScreenConfig.background_gradient.gradient_direction** ('top_corner_out', 'bottom_up') - Optional - Two different options for the direction of the background gradient. This direction only applies if you enable the `background_gradient.is_on` option. This is deprecated. Use `background` instead.
### Request Example
```json
{
"homeScreenConfig": {
"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"
}
}
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Configure Agent Pre-Start Chat Event Handler
Source: https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html/index_to=service-desks-nice
This JavaScript snippet configures an event handler for the 'agent:pre:startChat' event. It allows customization of the pre-start chat payload, including customer name and custom fields, which must be valid case fields in your account for the chat to initiate successfully.
```javascript
instance.on({
type: 'agent:pre:startChat',
handler: (event) => {
event.preStartChatPayload = {
customerName: 'Happy customer',
consumerContact: {
customFields: [{
// This must be a valid case field defined in your account or the chat fails to start.
ident: 'field-name',
value: 'field-value';
}],
},
};
},
});
```