Key concepts
Everything you need to know to get started.
Overview
Web chat provides everything you need to quickly and easily install a first-class web widget on your website. Out of the box, you get a chat widget that works with multiple browsers (and on mobile devices), with built-in integrations with service desks. You also automatically get the latest features from IBM Design and IBM Research to improve the quality of your customers' conversational experience.
API Overview
Web chat renders directly onto your website and not into an iFrame. This gives you and the web chat API much more power to deeply integrate with your website and code base.
Configuration
When your page initializes the web chat widget, it passes in a configuration object that sets various immutable options. By editing the configuration object, you can control the appearance and behavior of Web Chat before your customers even see it. Configuration options enable you to specify the location of the web chat widget on your page, choose whether to use the IBM-provided launcher or your own, and more.
Instance methods
Each instance of web chat provides a collection of runtime methods your website can call any time after the instance is available on your website. These methods can be applied before or after the web chat is rendered on the screen. With these methods, you can open or close the web chat widget from a custom control, send messages to your assistant from your own functions, theme the web chat, dynamically update web chat text strings and more.
Events
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.
Theming
Web chat theming is based on Carbon Themes. In addition to choosing a base theme for your web chat as part of configuration, we also allow you to set many individual variables within the theme to further customize web chat to match your brand. Check out the tutorial on theming to see it all come together.
Rendering of response types
Web chat supports special rendering behavior you can use to customize your content. Web chat supports HTML, CSS, JavaScript, and a subset of Markdown in text responses from your dialog skill. In addition, you can create user-defined response types that your code knows how to handle. With user-defined response types, you can augment your dialog skill responses by injecting code from your website into web chat at run time.
Versioning
Web chat follows semantic versioning practices. Starting with version 2.0.0
, as part of the configuration options you can also select a specific version to use. Visit the web chat release notes to find out what's new.
You can select which version to use by updating the watsonAssistantChatOptions object of your embed code: the default is clientVersion="latest"
, which allows you to automatically get the latest features and fixes. Web chat is a continuously improving offering with new features and bug fixes releasing regularly. As such, we recommend keeping the default behavior and letting your web chat auto-update. If you are using any of the additional configuration options, writing over the web chat CSS, or overriding other undocumented (and discouraged) behavior, you can freeze on an exact version of Web Chat to avoid any customizations or overrides no longer working as intended.
If you are freezing the version of your web chat, we have defined the the structure of the version as follows: clientVersion="major.minor.patch"
. Generally, we will add exciting new features as minor releases so you can comfortably get the latest and greatest without any action on your end. You can decide whether you want all the latest features, only the latest minor features, or only the bug fixes by not including them in the version you set. For example, let's say the latest version we have available is 2.4.0
. If you want to stay on version 2 but still get the latest minor and patch releases, you can set clientVersion="2"
. If you want to stay on version 2.3
but still get the latest patch releases, you can set clientVersion="2.3"
. And if you want to lock your version completely, you can set clientVersion="2.3.1"
.
Best Practices for Testing
If you want to test the latest updates before updating your live web chat, we recommend the following practices. Start by freezing your live web chat. Then embed web chat with the latest version in a test environment, test until you are confident, and then update the version of your live web chat.
It's possible that major releases will require changes in your configurations. For these cases, we will add specific testing practices to the release notes. Generally, this might involve making a new assistant, copying your skills over, resolving the breaking changes, and then testing before updating your production assistant.
Security
Web chat undergoes external PEN tests and automatic code scans on a regular basis to find security issues like cross-site scripting (XSS) vulnerabilities. IBM has a variety of security and code quality safeguards in place. Learn more
You will also want to run your own security reviews to see how web chat fits in with your current web site structure and policies. Web chat is hosted on your site and would inherit any vulnerabilities your site already has. We recommend only serving content over https, making use of CSP, and other basic web security precautions.
Securing Messages
In addition to making sure the code is secure, web chat also has features around making sure your conversations are coming to us from your web chat in an authorized way. At your web chat configuration page inside Watson Assistant, you can turn on additional security features for web chat. These additional security features for web chat take on three main forms.
First, authenticating the request is coming from your website. Second, being able to authenticate an individual user is logged in. Lastly, being able to pass sensitive and encrypted user information into context.
Overview
Web chat message security is based around using signed a JWT identityToken
signed via a RS256 public/private key pair. Once you turn on security for web chat in Watson Assistant, any message sent from web chat will require an up to date identityToken
attached to it. Learn more
When your web chat is instantiated, you will want to listen for the identityTokenExpired event so you can update your token when web chat requires a fresh token.
Optionally, if you already have a identityToken generated when your page loads, you can provide the identityToken
as part of your configuration options and then listen for theidentityTokenExpired event for subsequent updates.
At any time you can also call the updateIdentityToken instance method to add information to the token at any time.
Token generation
In order to generate your identityToken
, you need a private/public key pair. The public key will be shared with Watson Assistant to verify your token on the web chat configuration page, and your private key you will use to generate the token.
Once you have your private key, you can use it to generate an identityToken
. Below is an example using NodeJS, but there are libraries available in all languages.
The token requires the sub
claim to be set and not change. This claim acts as the unique userID and must be set for both unauthenticated and authenticated users. It is recommended you also have a short lived exp
claim as well.
// Sample NodeJS code on your server.
const jwt = require('jsonwebtoken');
/**
* Returns a signed JWT generated by RS256 algorithm.
*/
function mockLogin() {
const payload = {
/*
* Even if this is an unauthenticated user, you should supply a userID in the sub claim to be used for billing.
* This will serve as our tracking of "unique users". For unauthenticated users, we recommend
* dropping a cookie in the browser so you can make sure the user is counted uniquely across visits.
*/
sub: 'some-user-id', // Required
// The exp claim is automatically added by the jsonwebtoken library. We recommend you set a short lived exp claim
// with whatever library you are using.
};
// The "expiresIn" option adds an "exp" claim to the payload. It is highly recommended you add an exp claim.
return jwt.sign(payload, process.env.YOUR_PRIVATE_RSA_KEY, { algorithm: 'RS256', expiresIn: '10000ms' });
}
Web site authentication
If you have web chat security turned on in Watson Assistant, you are required to supply a signed jwt on every request to Watson Assistant from web chat. Once you provide the token to web chat, it will be automatically included on each requests until it expires. The passed identityToken
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.
<script src="https://web-chat.global.assistant.watson.appdomain.cloud/loadWatsonAssistantChat.js"></script>
<script>
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
identityToken: 'YOUR_JWT',
onLoad: function(instance) {
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>
Once it expires, we will fire an event to let you know to provide an updated token along with a callback that will update the token and process any messages that are waiting for a new token.
window.watsonAssistantChatOptions = {
integrationID: 'YOUR_INTEGRATION_ID',
region: 'YOUR_REGION',
identityToken: 'YOUR_JWT',
onLoad: function(instance) {
instance.on({ type: 'identityTokenExpired', handler: function(event) {
// Perform whatever actions you need to take on your system to get a new token...
return new Promise(function(resolve, reject) {
// And then pass the new JWT into the callback and we will continue processing.
event.identityToken = 'YOUR NEW JWT';
resolve();
});
}});
instance.render();
}
};
User authentication
To add an authenticated a user with web chat, just add their unique identifier to the sub
claim. Once you set the claim, you cannot change it to another user. The sub
claim is used as the userID and is available under context.global.system.user_id
inside Watson Assistant.
The sub
claim 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 sub
syntax must meet the requirements for header fields as defined in RFC 7230 (all visible ASCII characters). Read more about removing user data
// Sample NodeJS code on your server.
const jwt = require('jsonwebtoken');
const RSA = require('node-rsa');
const rsaKey = new RSA(process.env.PUBLIC_IBM_RSA_KEY);
/**
* Returns a signed JWT. Optionally, also adds an encrypted user_payload. The userPayload is stringified JSON.
*/
function mockLogin(userID) {
const payload = {
sub: userID, // Required
// The exp claim is automatically added by the jsonwebtoken library. We recommend you set a short lived exp claim
// with whatever library you are using.
};
const token = jwt.sign(payload, process.env.YOUR_PRIVATE_RSA_KEY, { algorithm: 'RS256', expiresIn: '10000ms' });
return token;
}
User payload encryption
Optionally, you can also load an encrypted payload to the token. This information will be added to context. The public key used to encrypt the information is available to you from IBM in Watson Assistant. Watson Assistant then decrypts the data and adds it to context at context.integrations.chat.private.user_payload
. The data inside context.integrations.chat.private
will not be returned when a message is received.
Most people will use this encrypted area to pass sensitive information to Watson Assistant you don't want your customers to be able to see by inspecting network traffic. For instance, if the user is a VIP or not.
Others also use it to pass along additional tokens, like to provide SSO credentials for webhooks called from your dialog skill.
// Sample NodeJS code on your server.
const jwt = require('jsonwebtoken');
const RSA = require('node-rsa');
const rsaKey = new RSA(process.env.PUBLIC_IBM_RSA_KEY);
/**
* Returns a signed JWT. Optionally, also adds an encrypted user_payload. The userPayload is stringified JSON.
*/
function mockLogin(userID, userPayload) {
const payload = {
sub: userID, // Required
// The exp claim is automatically added by the jsonwebtoken library. We recommend you set a short lived exp claim
// with whatever library you are using.
};
if (userPayload) {
// If there is a user payload we encrypt it using the IBM public key. Should be encrypted to base64 format.
payload.user_payload = rsaKey.encrypt(userPayload, 'base64');
}
const token = jwt.sign(payload, process.env.YOUR_PRIVATE_RSA_KEY, { algorithm: 'RS256', expiresIn: '10000ms' });
return token;
}
Logging out
Web chat does not support changing the sub
claim used to submit the userID. To logout a user you must destroy the web chat.
If when your user logs out it creates a page reload, be sure to call instance.destroySession to remove any reference to the current session from the browser's cookies and storage. If you forget to call this, identityToken protected information will not be at risk, but web chat will try to connect to the previous session and fail.
If your logout method does not cause a full page reload, you should also call instance.destroy, which will remove the current instance of the web chat configured for that userID from the DOM and browser memory. You should still call instance.destroySession
as well.
Content-Security-Policy
If your website makes use of a Content-Security-Policy
, you will need to add some values to it to grant permissions to the web chat code.
You will need to add the following values to your CSP. The fonts.gstatic.com
entry is only required if you are using our default fonts.
Property | Additional Values |
---|---|
default-src | 'self' *.watson.appdomain.cloud fonts.gstatic.com 'unsafe-inline' |
connect-src | *.watsonplatform.net *.watson.appdomain.cloud |
Here is an example of a complete CSP meta tag that includes all of the required values:
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self' *.watson.appdomain.cloud fonts.gstatic.com 'unsafe-inline';connect-src *.watsonplatform.net *.watson.appdomain.cloud"
>
Avoiding the use of 'unsafe-inline'
If your CSP uses a nonce to whitelist elements such as script and style tags, instead of using 'unsafe-inline' to blanket allow all such elements, you can provide that nonce value to the widget as part of the widget options and it will set that nonce on any of the script or style elements that it dynamically generates.
Such a CSP may look like the following.
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self' *.watson.appdomain.cloud fonts.gstatic.com 'nonce-<server generated value>';connect-src *.watsonplatform.net *.watson.appdomain.cloud"
>
You can apply the nonce by setting the option like below.
window.watsonAssistantChatOptions = {
integrationID: "YOUR_INTEGRATION_ID",
region: "YOUR_REGION",
serviceInstanceID: "YOUR_SERVICE_INSTANCE",
cspNonce: "<server generated value>",
onLoad: function(instance) {
instance.render();
}
};
Billing
Watson Assistant charges based on number of unique users every month. In order to track unique users, web chat gives you two methods. First, we allow you to pass in a de—identified userID either as part of a secure JWT or as a string passed to instance.updateUserID. If you are using our advanced security features, this userID takes the form of a sub
claim in a JWT.
Alternatively, if you are not using web chat&pos;s advanced security features, you can rely on web chat to generate a cookie with an anonymous generated ID that is placed in the browser to make sure you are not billed multiple times for the same user. We recommend that you provide the userID on your own and avoid us having to set the cookie on your site. Read more about web chat and cookies.
GDPR and cookie policies
Web chat stores an ID to identify the current session for the length of the browser being open. This allows web chat the ability to keep the current session open as your users navigate around your page. Once the user closes the browser, this information is removed.
If you supply web chat with a userID, the only data or cookies that will be stored on the browser will be the current session information. This userID can be used to delete the user's data on request, as it is also passed as the customer_id
portion of the X-Watson-Metadata
HTTP header. Because of this, the userID syntax must meet the requirements for header fields as defined in RFC 7230 (all visible ASCII characters). Read more about removing user data Learn more
If you do not supply web chat with a unique userID, we will add a 1st party cookie with a generated anonymous ID. The cookie will remain active for 45 days to make sure we don't count the same user multiple times in the same month and pollute billing metrics.
Web chat keeps analytics on what features of web chat are used so we can continually improve our user experience. None of the information collected makes the end user identifiable to IBM. Web chat does not track users across different web sites and we only make note of behavior inside web chat.
Language support
Web chat has built in language support for all the languages Watson Assistant supports. You can update to a different set of language strings in the web chat wholesale, or you can pick and choose what strings to change individually. Learn more
Accessibility
Web chat aims for WAC 2.1 AA compliance. It is tested both manually with screen readers and via automated procedures on a continual basis.
Browser support
Web chat supports a wide variety of devices and platforms. As a rule, if the last two versions of a browser account for more than 1% of all desktop or mobile traffic, web chat supports that browser.
Like on most mobile web sites, our mobile support requires you to have <meta name="viewport" content="width=device-width, initial-scale=1"></meta>
set in your <head>
element for optimal results.
Web chat supports the the following browsers (including the two most recent versions, except as noted):
- Chrome
- Safari
- Mobile Safari
- Chrome for Android
- Internet Explorer 11 (most recent version only)
- Edge (Chromium and non-Chromium)
- Firefox
- Firefox ESR (most recent ESR only)
- Opera
- Samsung Mobile Browser
- UC Browser for Android
- Mobile Firefox
Next, see the tutorials for code examples, or the API documentation for a deeper dive into web chat.