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 = {
    // A UUID like '1d7e34d5-3952-4b86-90eb-7c7232b9b540' included in the embed code provided in Watson Assistant.
    integrationID: "YOUR_INTEGRATION_ID",
    // Your assistants region e.g. 'us-south', 'us-east', 'jp-tok' 'au-syd', 'eu-gb', 'eu-de', etc.
    region: "YOUR_REGION",
    // A UUID like '6435434b-b3e1-4f70-8eff-7149d43d938b' included in the embed code provided in Watson Assistant.
    serviceInstanceID: "YOUR_SERVICE_INSTANCE_ID",
    // The callback function that is called after the widget instance has been created.
    onLoad: function(instance) {
      // The instance returned here as many methods on it we will document on this page.
      instance.render();
    }
  };

  setTimeout(function(){const t=document.createElement('script');t.src='https://web-chat.global.assistant.watson.appdomain.cloud/loadWatsonAssistantChat.js';document.head.appendChild(t);});
</script>

A web chat instance methods are broken up into the following sections: Chat Window, Security, Theming, Events, Languages, and Miscellaneous.

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

Requests the current messages list to autoscroll to the bottom (to the last set of messages from either the user or from the bot). 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();

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

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.

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

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 ICU Message Format JSON representations of all of the languages that are supported by both Watson Assistant 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 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 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).

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. If it recommended you call the updateLocale method before you call instance.render().

This method returns a Promise that succeeds if the widget successfully renders.

Example

// web chat makes an asynchronous request to get need data to render in spanish.
instance.updateLocale('es').then(function() {
  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);

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

Returns the version number of the widget code.

Example

instance.getWidgetVersion();