Oracle Cloud Infrastructure Documentation

Oracle Web

The Digital Assistant Client SDK for Oracle Web provides you with a widget that enables you to run a skill in a web page. Using the SDK, you can customize the look and behavior of this widget.

The SDK connects to the Oracle Chat Server, the intermediary between the Oracle Web channel configured in Oracle Digital Assistant and the client. The chat server then passes messages to the skill for processing and delivers the skill's response to the client.
Note

The Oracle Web Channel doesn't store messages when the client has disconnected from the server. It only delivers messages to connected clients. The SDK does not support multi-device login; it supports only one client per user.

This SDK works with instances of Oracle Digital Assistant that were provisioned on Oracle Cloud Infrastructure (sometimes referred to as the Generation 2 cloud infrastructure). If your instance is provisioned on the Oracle Cloud Platform (as all version 19.4.1 instances are), you can use the legacy JavaScript SDK.

What Do You Need?

  • An Oracle Web Channel. Creating the channel generates the Channel ID and the Secret Key that you need to initialize the chat app.
  • The URL of the Oracle Chat Server.
  • The Oracle Web SDK (located under Oracle Native Client SDKs for OCI Native Environments) from Oracle Technology Network’s ODA and OMC download page. Download this ZIP and extract it to your local system. This ZIP includes a user guide that describes the SDK's classes and a sample app that demonstrates many of its features.

Configure the Oracle Web Channel

You can configure the channel to connect to the Oracle Chat Server in two modes: authenticated (to protect access to the channel) or unauthenticated.
  • Authenticated mode – Authentication is enforced using JSON Web Tokens (JWT). The backend server generates these tokens using the Secret Key generated from the Oracle Web channel when a user authenticates with the web app. The server then sends the tokens the client, which is usually a browser. These tokens are then sent on every HTTP request, thus allowing the server to authenticate the user. The information contained within the token is signed by a private key which is owned by the server. When the server gets the token back from the client, it compares the signature sent by the client with the one that it will generate with its private key. The token is valid when the two signatures are identical.
    When the client needs to establish a web socket connection with the chat server, it first requests a JWT token from the backend server and then adds the token to the Authorization header in its call to the chat server.

    Tip:

    This article steps you through running the SDK with an authenticated channel.
  • Unauthenticated mode – Use the unauthenticated mode when the client can't generate signed JWT tokens, when no authentication mechanism is in place, or when the client widget is already secured and visible to authenticated users.
To configure the Oracle Web channel:
  1. Choose Development, then Channels from the menu.
  2. Choose Users.
  3. Click Add Channel and then Oracle Web as the channel type.
  4. Complete the dialog:
    • Enter the channel name.
    • For authenticated connections:
      • Switch on the Client Authentication Enabled toggle to determine whether the SDK is connecting to client authentication-enabled channel.
      • Enter a list of domains that can access the channel. Enter an asterisk (*) for unrestricted access.
      • In the Max. Token Expiration (Minutes) field, set the maximum amount of time for the JWT token.
    • For unauthenticated connections:
      • Switch off Client Authentication Enable toggle.
      • Enter a list of domains that can access the channel. Enter an asterisk (*) for unrestricted access.
    • Set the Session expiration time.
    • Click Create. Oracle Digital Assistant will generate the Channel ID and the Secret Key that you need to initialize the SDK. Keep it close at hand because you'll need them when configuring the HTML page to host the chat widget.
  5. Route the channel to your skill or digital assistant.
  6. Switch Channel Enabled to On.

Install the SDK

Install the SDK by updating the <script> tag in an HTML page with the code that we provide:
  1. In the extracted ZIP file of the downloaded Oracle Web SDK, locate the web-sdk.js file (located in the native-client-sdk-js directory).
  2. Save web-sdk.js (located in the native-client-sdk-js directory of the extracted ZIP) in your project directory. Note the file location, because you'll need it to define the <WebSDK URL> property in the <script> tag's code.
  3. Add the following <script> tag towards the end of the <head> element of the HTML page:
    <script>
        var chatSettings = {
            URI: '<Server URI>',
            channelId: '<Channel ID>',
            userId: '<User ID>'
        };
        function initSdk(name) {
            // Default name is Bots
            if (!name) {
                name = 'Bots';
            }
            setTimeout(() => {
                const Bots = new WebSDK(chatSettings); // Initiate library with configuration
                Bots.connect()                         // Connect to server
                    .then(() => {
                        console.log("Connection Successful");
                    })
                    .catch((reason) => {
                        console.log("Connection failed");
                        console.log(reason);
                    });
                window[name] = Bots;
            });
        }
    </script>
    <script src="<WebSDK URL>" onload="initSdk('<WebSDK namespace>')">
  4. Define the following properties:
    • URI - The URI of the Oracle Chat Server. This is a required property.
    • channelId - The Channel ID that's generated when you create the Oracle Web channel. This property is required because connects the widget to the underlying skill.
    • userId - A user ID. You can provide this value, but the SDK will generate this value if you haven't already provided it. This property is optional for unauthenticated connections.
    • <WebSDK URL> - The location of the web-sdk.js file. For example: "./scripts/web-sdk.js". This is a required property.
    • <WebSDK namespace> - Use this namespace to invoke the public APIs. For example, if you set the namespace to Bots, then you invoke the APIs as Bots.<API>(). To find out more about the various functions and events, refer to the user guide (available as both a readme and HTML doc) that's included with in Oracle Web SDK ZIP file.

Configure Client Authentication

For authenticated mode, you need to define the URI, and channelId, and userId properties. In addition you configure the <script> tag code as follows:
  • Pass the clientAuthEnabled property as true.
  • Include a function that can be used to generate and pass the JWT token that's set in the Authorization header (Authorization: Bearer <JWT>).
    The header must have the following token claims: channelId, URI, userId, and the claim names iat (issued at time), and exp (expiration time). iat signifies the time at which the token was issued. This must a number that represents the seconds that have elapsed since the UNIX epoch. exp must be a number representing the seconds that have elapsed since the UNIX epoch. We recommend setting the expiration time to at least 30 minutes after the issued at time (iat). The decoded header looks something like this:
    {
    
     "alg": "HS256",
    
     "typ": "JWT"
    
    }
    An example of the decoded body looks something like this:
    {
    
      "iat": 1569828182,
    
      "exp": 1569831782,
    
      "channelId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    
      "userId": "John"
    
    }
    Note

    The token illustrated by this example is not signed. The actual tokens are signed by channel's Secret Key.
The code for authenticated mode is as follows:
<script>
    var chatSettings = {
        URI: '<Server URI>',
        clientAuthEnabled: true
    };
    var generateToken = function() {
        return new Promise((resolve) => {
            fetch('https://yourbackend.com/endpointToGenerateJWTToken').then((token) => {
                resolve(token);
            })
        });
    }
    function initSdk(name) {
        // Default name is Bots
        if (!name) {
            name = 'Bots';
        }
        setTimeout(() => {
            const Bots = new WebSDK(chatSettings, generateToken);  // Initiate library with configuration
            Bots.connect()                                                  // Connect to server
                .then(() => {
                    console.log("Connection Successful");
                })
                .catch((reason) => {
                    console.log("Connection failed");
                    console.log(reason);
                });
            window[name] = Bots;
        });
    }
</script>
<script src="<WebSDK URL>" onload="initSdk('<WebSDK namespace>')">

Customize the Chat Widget

You can customize various aspects of the chat widget, such as its layout and icons, colors, and text.

Tip:

This article gets you acquainted with the various customization properties.

Network Configuration

You intiate the SDK using these connection properties. The sample app that ships with the SDK provides an example of how to set them in its scripts/settings.js file.
Property Name Description Required? Default Value
URI The URL of the Oracle Chat Server Yes N/A
channelId The Channel ID of the Oracle Web Channel Yes N/A
userId A unique identifier for the user. If you don't provide this, Oracle Digital Asssistant generates one. No A randomly generated value
clientAuthEnabled Determines whether the SDK connectes to a channel where client authentication has been enabled. As described in Configure Client Authentication, you set this to true to connect to channel with authentication enabled and use the JWT token. Yes false

Feature Flags

Use the Feature Flag properties for:
  • Secure connections
  • Pill-shaped action buttons
  • Audio narration of skill responses.
  • Attachment sharing
  • Disabling clicks on previous (out of focus) messages
  • Autocomplete user input
For example:

    <script>
        var chatWidgetSettings = {
            enableTimestamp: true,
            showConnectionStatus: true,
            conversationBeginPosition: 'bottom',
            openChatOnLoad: true,
            position: {bottom: '2px', right: '2px'},
            displayActionAsPills: true,
            initUserHiddenMessage: 'Hello',
            embedded: true,
            targetElement: 'chat-container',    
            embedTopScrollId: 'top-text',
            customHeaderElementId: 'custom-header',
            botButtonIcon: 'images/bot-button.png', 
            logoIcon: 'images/bot-white.png', 
            botIcon: 'images/bot-green.png',        
            personIcon: 'images/user-icon.png',
            URI: YOUR_URI,
            channelId: YOUR_CHANNELID,

         };

...
    </script>
Property Name Description Required? Default Value
disablePastActions Disables interactions (button clicks) with the messages that users have already interacted with. The allowed values are all, none, or postback. The behavior enabled by this property is independent of the digital assistant-level configuration for disabling the selection of past actions. You need to set the two separately. No all
displayActionsAsPills Displays pill-shaped action buttons. No false
enableAttachment Configures attachment sharing. No true
enableAutocomplete Set to true to enable the skill to autocomplete the user request using the idealized user requests entered as Autocomplete Suggestions in the Create Intent page. The skill ouputs these suggestions when the user enters three or more characters. It also sets off the words in the user input that match the suggested phrases in bold. No false
enableBotAudioResponse Configures the skill responses. The skill responses are read aloud by the Web API. To select the voice for reading messages from a skill or digital assistant aloud, set this proprety to true and then define the skillVoices array. No false
enableClearMessage Enables the clear message button in the chat widget header. No false
enableHeadless Enables you to use the Oracle Web SDK without its UI so that you can develop your own chat UI. No false
enableLocalConversationHistory Enables the previous conversation that's associated with a given userId to be loaded in the browser when the widget has been initialized. No false
enableLongPolling Use HTTP requests when the websocket fails to connect. No false
enableSecureConnection Configures secure communication (https v. http and wss v. ws). No true
enableSpeech When set to true, this property enables the microphone for voice recognition. For example:
chatWidgetSettings = {
    URI: 'idcs-oda-example.com',
    channelId: '9999b1-f99a-9999-999ee-df9d99999d',
    enableSpeech: true
};
No false
enableSpeechAutoSend When set to true (the default), the user's speech response is automatically sent to the chat server (and displays as a sent message in the chat widget). When set to false, the user's speech response is rendered in the message text field before it's sent to the chat server so that the user can modify it before sending it manually, or delete the message. No true
enableTimestamp Enables the timestamp for messages and the "read" symbol. No true
openChatOnLoad Expands the chat widget when the page is loaded. No false
openLinksInNewWindow Overrides the user's browser preference by opening links in a new window. No false
showConnectionStatus Enables the connection status to display in the chat widget header. No false
showPrevConvStatus Displays status messages at the end of older messages from previous conversations. No true
showTypingIndicator Displays a chat bubble when waiting for a response. No true

Functionality

Use the Functionality properties to:
  • Imitate a skill-initiated conversation.
  • Embed content to the top and bottom of the chat window that either scrolls, or is stationary (sticky).
  • Set the locale.
  • Set debug mode.
  • Set the locale and voice for speech synthesis.
Property Name Description Required? Default Value
customHeaderElementId Names the ID of the <div> element that's added to the header of the chat widget. For example, the custom-header div in the following snippet is referenced as customHeaderElementId: 'custom-header' to display Your Pizzabot within the header of the chat widget.
<div id="custom-header" style="padding: 0; text-align: initial">
        <h1>Your Pizzabot</h1>
    </div>
The Web SDK tutorial describes how to configure this property and set scrolling and non-scrolling for chat widget elements.
No N/A
delegate An object that sets a delegate to receive callbacks before certain events occur in a conversation. No N/A
embedBottomScrollId The ID of the element that's added as the scrolling content at the bottom of the chat. Use this property to add custom content in the chat widget's conversation view. No N/A
embedBottomStickyId The ID of the element used for the sticky content that appears at the bottom of the chat. Use this property to add custom content in the chat widget's conversation view. No N/A
embedded When you set this to true, you activate the embedded mode for the chat widget. You also need to name the div element that houses the widget in the targetElement property. No false
embeddedVideo Enables the embedding of a YouTube video link in a text message. No false
embedTopscrollId The ID of the div element that's added as a scrolling content at the top of the chat widget. No N/A
embedTopStickyId The ID of the div element that's used for the sticky content that appears at the top of the chat widget. Use this property to add custom content in the chat widget's conversation view. For example, the top-text div element in the following snippet is referenced as embedTopStickyId: 'top-text':

<div id="top-text" style="padding: 0; text-align: initial">
<p>Talk to Pizzabot to order your pizza.</p>
</div>
The Web SDK tutorial describes how to configure this property and set scrolling and non-scrolling for chat widget elements.
No N/A
enableAutocompleteClientCache Enables client side caching to minimize server calls when the autocomplete feature is in use. No false
i18n An object that contains locale fields. Each locale maintains i18n key-value pairs for the text strings used in the widget. No {'en-us':{…}}
For example:
"i18n": {
                "en-us": {
                    "chatTitle": "Pizza King"
                }
            } 
initBotAudioMuted This flag, which only applies when the enableBotAudioResponse feature flag is set to true, determines if the skill is initially muted, or can read messages aloud. Setting it to true (the default value), mutes the skill. Setting it to false enables the skill to read messages aloud. No true
initUserHiddenMessage A message that's used to initiate a conversation. This message, which can be text string or a message payload, is sent when chat widget is ready but doesn't actually display in chat. For example: initUserHiddenMessage: 'Hi' No N/A
initUserProfile Updates the user profile before the start of a conversation. The format of the profile payload must be { profile: {...} }. For example:
initUserProfile : {
    profile:{
    givenName: 'First',
    surname: 'Last',
    email: 'first.last@example.com',
    properties: {
        lastOrderedItems: '1 medium pepperoni'
    }
}
}
This function updates the user context before the initial "hidden" message is sent by initUserHiddenMessage to start the conversation. As a result, the user profile can be reflected in the first response message to the user. For example, the skill can greet the user with a message like "Welcome back, John Smith! Your last order was a medium pepperoni pizza."
No N/A
isDebugMode Enables debug mode. No false
locale The default locale for the widget's text strings. The locale passed during initialization has a higher preference over users’ browser locales. If there isn’t an exact match, then the SDK attempts to match the closest language. For example, if the locale is 'da-dk', but i18n translations are provided only for 'da', then the 'da' translation is used. In absence of translations for passed locale, translations are searched for and applied for the browser locales. In absence of translations for any of them, the default locale, 'en' is used for translations. No en-us
messageCacheSizeLimit The maximum number of messages that get save in localStorage at a time. No 2000
readMark Denotes that a skill's messages have been read. It's disabled when you set enableTimestamp to false. No A tick mark (
'✓'
)
skillVoices An array of device preferred device voices. This array, which is used when enableBotAudioResponse is set to true, enables you to select the voice that reads the messages from the skill or digital assistant aloud. As described in Response Narration, each item in this array is an object that can have two fields: lang (required) and name, which is optional. The first item that matches a voice that’s available in the system will be used as the narrator's voice. No The system language (when no preferences can be matched)
targetElement Names the div element where the chat widget gets embedded in the web page. The chat-container div element in the following snippet is referenced as targetElement: 'chat-container', for example:
        <div id="chat-container" class="chatbox" 
            style="height: 600px; width: 400px; padding: 0;
            text-align: initial">
        </div>
Check out the Web SDK tutorial to find out how to add and style the div element.
No widgetDiv
typingIndicatorTimeout Sets the number of seconds after which the typing indicator is automatically removed if the chat widget has not yet received the response. No 20

Layout

Use the layout properties to:
  • Set the position of the widget within the web page.
  • Set chat widget's dimensions, colors, and font style.
  • Set the padding for the messages within the widget.
  • Set the position of the notification badge icon with respect to bot button.
  • Set the starting position for the conversation within the widget.
For example:
     <script>
        var chatWidgetSettings = {
            URI: YOUR_URI,
            channelId: YOUR_CHANNELID,
            font: '14px "Helvetica Neue", Helvetica, Arial, sans-serif', //layout modification property
            height: '60vh', //layout modification property
            width: '20vw',  //layout modification property
             "colors": {    //custom colors property  
                "branding": "#01538A",
                "text": "#B20637"
            },
         }
                
...
    </script>
Property Description Required? Default Value
badgePosition The position of the badge icon with respect to the icon button. No {"top": "0", "right": "0"}
colors The colors used in the chat widget. No {"branding": "#1B8FD2", "text": "#212121", "textLight": "#737373"}
conversationBeginPosition The starting position for conversation in the widget. If set to top, the first messages appear at the top of the widget. If set to bottom, then the conversation starts at the bottom. No top
font The font used in the chat widget. No 16px "Helvetica Neue", Helvetica, Arial, sans-serif
height The height of a chat width as set by one of the <length> data type values. No 70vh
messagePadding The padding around messages in the chat widget. No 15px
position The placement of the chat widget in the browser window. This should be passed as a JSON object. No {bottom: '20px', right: '20px'}
width The width of the chat widget as set to one of the <length> data type values. No 30vw

Custom Icons

You can customizes the icons, including the ones for the skill icon, the chat logo icon, and the avatar icons for the skill and user.

You can pass the URL of the image asset for these icons:
...
    botButtonIcon: 'images/Robot.png',
    logoIcon: 'images/logo.png',
    botIcon: 'images/Robot.png',
    personIcon: 'images/userIcon.png',
For some icons, you can either use the URL or pass a Scalable Vector Graphics (SVG) string:
const chatSettings = {
    ...,
    clearMessageIcon: 'https://cdn4.iconfinder.com/data/icons/kids-2/128/kids_kid_boy-32.png',
    micIcon: '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none" opacity=".1"/><path d="M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h4v1h-7v2h6c1.66 0 3-1.34 3-3V10c0-4.97-4.03-9-9-9z"/></svg>'
};
For the icons that support SVG strings, you can pass the raw SVG data, which the chat view renders as an inline SVG.

Tip:

SVG strings load faster than image assets. They also let you animate the image and change its color. The theme color is applied to SVG strings for attachment, send, and mic buttons, but not the other image assets.
Property Description SVG String Compatible?
attachmentIcon The attachment upload icon Yes
audioIcon The audio attachment icon, displayed when attachment source URL is not reachable No
audioResponseOffIcon The icon for the toggle button when audio responses are turned off Yes
audioResponseOnIcon The icon for the toggle button when audio responses are turned on Yes
botButtonIcon The skill bot button, displayed when the chat widget is minimized. No
botIcon The icon that displays alongside the skill's reponse message. This skill icon only displays if you provide this icon. Otherwise, no icon displays. No
chatBubbleIcon The icon for the loading chat bubble. You can also resize this using the chatBubbleIconHeight and chatBubbleIconWidth properties. Yes
clearMessageIcon The clear message button icon that's located in the widget header Yes
clearMessageIcon The icon for the clear messages button that's located in the chat view header Yes
closeIcon The icon for the button, located in the chat view header, that minimizes the chat view. Yes
errorIcon The URL for the image used for the error icon. No
fileIcon The file attachment icon No
imageIcon The image attachment icon, which is displayed when the attachment source cannot be reached. No
logoIcon Chat logo icon, displayed in the header of the chat widget No
micIcon The mic button icon Yes
personIcon The icon that displays alongside user messages. This person icon only displays if you define this icon. Otherwise, no icon displays. No
sendIcon The send message button icon Yes
sendIcon The send message button icon Yes
videoIcon The video attachment icon, which is displayed when the attachment source URL cannot be reached. No
You can also resize the icon for the loading chat bubble icon (enabled with chatBubbleIcon).
Property Name Description Required? Default Value
chatBubbleIconHeight The height of the loading chat bubble icon. No 42px
chatBubbleIconWidth The width of the loading chat bubble icon. No 56px

Custom Colors

You can customize the widget's colors. As illustrated by the following snippet, you define the keys using hexadecimal colors.
"colors": {
    "branding": "#e00",
    "text": "#545454"
}
Note

You can set an image for conversationBackground, headerBackground, and footerBackground. These fields can accept any parameters that can be passed to the CSS background background property. For example:
{ colors: { conversationBackground: "no-repeat url('https://images.unsplash.com/photo-1582580470647-e3be5274d6a0?ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80")' }}
Key Description Default Value
branding The primary color for the widget branding. The color used as the header background and as the hover color on footer buttons. #1B8FD2
text The text color for messages in the chat widget. #212121
textLight The text color of secondary text in messages (such as the card descriptions in the chat widget). #737373
botMessageBackground The color for the background of the skill's response message bubble #e5f1ff
botText The color for the text in a message sent by the skill #212121
userMessageBackgound The color for the background of the skill's message bubble #ececec
userText The color for the text in a message sent by the user #212121
cardBackground The background color for a card #ffffff
conversationBackground The color used for the background of the conversation pane #ffffff
headerBackground The background color for the chat widget’s header #1B8FD2
footerBackground The color used for the backgound of the footer #ffffff
notificationBadgeBackground The background color for the message notification badge #e6081a
notificationBadgeText The text color for the message count in notification badge #ffffff

Custom Text

You can customize the following strings and provide them as localized text. As illustrated by the following object, localization requires you to provide a valid locale for each entry. You need to update all keys for locales other than en-us. If you don't, then en-us translations are displayed for the missing values.
"i18n": {
    "fr": {
        "chatTitle": "Soutien"
    },
    "en-us": {
        "chatTitle": "Support"
    },
    "es": {
        "chatTitle": "Apoyo"
    },
    "zh-cn": {
        "chatTitle": "支持"
    }
}
Key Description Default Value
audioResponseOff The tooltip that appears when the user hovers over an audio utterance "on" button in header. Audio response off
audioResponseOn The tooltip that appears when the user hovers over the audio utterance "off" button in header. Audio response on
cardImagePlaceholder The placeholder text that displays while the card image is fetched and loaded. Loading image
chatTitle The title of the chat widget that is displayed in the header. Ask
chatSubtitle Sets the subtitle of the chat view, which is displayed below the title on the chat view header. If the subtitle flag is set and either (or both) the showConnectionStatus and showTypingIndicator flags are set to true, then the subtitle is displayed instead of either the connection status or the typing indicator. N/A
clear The tooltip that appears when the user hovers over the Clear Messages button in the header. Clear
close The tooltip that appears when the user hovers over the close widget button in the header. Close
closing The status text that displays while the connection between chat widget and server is closing. Closing
connected The status text that displays while the connection between chat widget and server is established. Connected
connecting The status text that displays when the chat widget connects to the chat server. Connecting
disconnected The status text that displays when the connection between chat widget and server has closed. Disconnected
inputPlaceholder The placeholder text that appears in the user input field. Type a message
noSpeechTimeout The status text that's displayed when the Chat Server is unable to recognize the voice. Could not detect the voice, no message sent.
previousChats The status text that displays at the end of older messages. Previous conversations
requestLocation The text that displays while the user location is requested. Requesting location
requestLocationString The error text that displays when the user denies the location request. Cannot access your location. Please allow access to proceed further.
retryMessage The text that displays when the user message has not been sent to the server. Try again
send The tooltip appears when the user hovers over the send button in the footer. Send
speak The tooltip that appears when the user hovers over the speak button in the footer. Speak
upload The tooltip that appears when the user hovers over the upload button in the footer. Upload Document
uploadFailed The error text that displays when an upload fails. Upload Failed.
uploadFileSizeLimitExceeded The error text that displays when the size of the upload file exceeds the limit. Upload Failed. File size should not be more than 25MB.
uploadUnsupportedFileType The error text that displays when an upload is attempted for an unsupported file type. Upload Failed. Unsupported file type.
utteranceGeneric The fallback description for the response message that's used in utterance Message from skill.

Customize CSS Classes

You can override the widget's CSS classes with custom style rules to further customize the look and feel.
Class Component
oda-chat-wrapper The wrapper for entire chat component
oda-chat-button The collapsed chat component button
oda-chat-notification-badge The notification badge for messages that haven't been viewed.
oda-chat-widget The expanded chat component, which wraps the widget header, conversation, and footer.
oda-chat-header The chat widget header
oda-chat-logo The logo on the widget header
oda-chat-title The title on the widget header
oda-chat-connection-status The connection status. Each connection value has its own class as well, such as oda-chat-connected, oda-chat-disconnected, or oda-chat-connecting.
oda-chat-connected Applied as a sibling to oda-chat-connection-status when the widget is connected to server
oda-chat-connecting Applied as a sibling to oda-chat-connection-status when the widget is connecting to server
oda-chat-disconnected Applied as a sibling to oda-chat-connection-status when the widget is disconnected from server
oda-chat-closing Applied as a sibling to oda-chat-connection-status when the widget is disconnecting from server
oda-chat-header-button The common class for all header buttons
oda-chat-button-clear The clear messages button
oda-chat-button-narration The skill's audio response toggle button
oda-chat-button-close The close widget button
oda-chat-conversation The container for the conversation
oda-chat-message The common wrapper class for all chat messages
oda-chat-left The wrapper for the skill message
oda-chat-right The wrapper for the user message
oda-chat-icon-wrapper The wrapper for the skill or for a person that's displayed alongside the message.
oda-chat-message-icon The image for the skill or for a person that's displayed alongside the message.
oda-chat-message-bubble The message bubble
oda-chat-message-actions The action buttons wrapper
oda-chat-message-global-actions The global action buttons wrapper
oda-chat-message-action-postback The postback action button
oda-chat-message-action-location The location request action button
oda-chat-card The card message
oda-chat-footer The chat widget footer
oda-chat-footer-button The common class for all footer buttons
oda-chat-button-upload The upload file button
oda-chat-button-send The send message button
oda-chat-user-input The user input text area

Features

Autocomplete

Autocomplete minimizes user error by providing effective phrases that can be used as both direct input and as suggestions. To enable this feature, update the widget settings with enableAutocomplete: true and add a set of optimized user messages to the Create Intent page. Once enabled, a popup displays these messages after users enter three or more characters. The words in the suggested messages that match the user input are set off in bold. From there, users can enter their own input, or opt for one of the autocomplete messages instead.
Description of autocomplete_phrase_list.png follows

When a digital assistant is associated with the Oracle Web channel, all of the sample utterances configured for any of the skills registered to that digital assistant can be used as autocomplete suggestions.

Delegation
The delegation feature sets a delegate to receive callbacks before certain events in the conversation. To set a delegate, pass the delegate parameter, or use the setDelegate method. The delegate object may optionally contain the beforeDisplay, beforeSend, and beforePostbackSend delegate functions.
const delegate = {
    beforeDisplay(message) {
        return message;
    },
    beforeSend(message) {
        return message;
    },
    beforePostbackSend(postback) {
        return postback;
    }
}

new Bots(delegate);
beforeDisplay

The beforeDisplay delegate allows a skill's message to be modified before it is displayed in the conversation. The message returned by the delegate is used to display the message. If it returns a falsy value, like null, undefined, or false, then no message is sent.

beforeSend

The beforeSend delegate allows a user message to be modified before it is sent to the Oracle Chat Server. The message returned by the delegate is sent to the skill. If it returns a falsy value, like null, undefined, or false, then no message is sent.

beforePostbackSend

The beforePostbackSend delegate is similar to beforeSend, just applied to postback messages from the user. The postback returned by the delegate is sent to the skill. If it returns a falsy value, like null, undefined, or false, then no message is sent.

Embedded Mode
In addition to the other settings that customize the look and feel of the widget that runs the chat, you can embed the widget itself in the Web page by:
  • Adding embedded: true.
  • Defining the targetElement property with the ID of the DOM element (an HTML component) that's used as the widget's container (such as 'container-div' in the following snippet).
<head>
    <meta charset="utf-8">
    <title>Oracle Web SDK Sample</title>
    <script src="scripts/settings.js"></script>
     <script>
        var chatWidgetSettings = {
            URI: YOUR_URI,
            channelId: YOUR_CHANNELID,
            embedded: true,
            targetElement: 'container-div'
...

    </script> 
</head>
<body>
    <h3 align="center">The Widget Is Embedded Here!</h3>
</body>
           <div id="container-div" 
                style="height: 600px; width: 380px; padding: 0; text-align: initial">
            </div>
Note

The widget occupies the full width and height of the container. If it can't be accommodated by the container, then the widget won't display in the page.
Headless SDK
Similar to headless browsers, the SDK can also be used without its UI. The SDK maintains the connection to the server and provides APIs to send messages, receive messages, and get updates on the network status. You can use these APIs to interact with the SDK and to update the UI. To enable this feature, pass enableHeadless: true in the initial settings. The communication can be implemented as follows:
  • Sending messages - Calls Bots.sendMessage(message) to pass any payload to server.
  • Receiving messages - Responses can be listened for using Bots.on('message:received', <messageReceivedCallbackFunction>).
  • Get connection status update - Listens for updates on the status of the connection using Bots.on('networkstatuschange', <networkStatusCallbackFunction>). The callback has a status parameter that is updated with values from 0 to 3, each of which maps to WebSocket states:
    • 0 : WebSocket.CONNECTING
    • 1: WebSocket.OPEN
    • 2: WebSocket.CLOSING
    • 3: WebSocket.CLOSED
Long Polling

The SDK uses WebSockets to connect to the server and converse with skills. If for some reason the WebSocket is disabled over the network, traditional HTTP calls can be used to chat with the skill. This feature is known as long polling because the SDK must continuously call, or poll, the server to fetch the latest messages from skill. This fallback feature can be enabled by passing enableLongPolling: true in the initial settings.

Voice Recognition

Setting enableSpeech: true enables the microphone button to display in place of the send button whenever the user input field is empty.

Your skill can also utilize voice recogniction with the startVoiceRecording(onSpeechRecognition, onSpeechNetworkChange) method to start recording and the stopVoiceRecording method to stop recording. (These methods are described in the User's Guide that's included with the SDK.)

Using the enableSpeechAutoSend flag, you can configure whether or not to send the text that’s recognized from the user’s voice directly to the chat server with no manual input from the user. By setting this property to true (the default), you allow the user’s speech response to be automatically sent to the chat server. By setting it to false, you allow the user to edit the message before it's sent to the chat server, or delete it.

Response Narration
The SDK enables narration of the chat server's responses by leveraging the device’s speech synthesis APIs. You can define the voice that reads the skill or digital assistant messages aloud by setting enableBotAudioResponse to true and then by defining the skillVoices array, which prioritizes the voice preferences. The objects in this array use a lang field and an optional name field to describe the voices that the device can use for spoken content. The following example illustrates a skillVoices array for iPhone voices.
const settings = {
    ...,
    enableBotAudioResponse: true,
    skillVoices: [{
        lang: 'en-US',
        name: 'Samantha'
    }, {
        lang: 'en-US',
        name: 'Alex'
    }, {
        lang: 'en-UK'
    }]
}

The SDK searches for these voices in the order that they are passed. It then selects the first complete match to be the voice of the narrator. If the SDK can't find an exact match, then it selects the first match based on the lang value alone. If there's no matching lang value, then the SDK uses the device’s default language.

Message Model

To use features like headless mode and delegate, you need to understand both user and skill messages. Everything that's received or sent from the Oracle Chat Server is represented as a message, one that's sent from the user to the skill, or from the skill to the user.

Base Types
These are the base types used in all messages sent from the user to the skill and vice versa. They are the building blocks of all messages.
Attachment
Represents an attachment that's sent by the user.
Name Description Type Required?
title The attachment title string No
type The attachment type string (valid values: audio, file, image, video) Yes
url The download URL for the attachment string Yes
For example:
{
    "title": "Oracle Open World Promotion",
    "type": "image",
    "url": "https://www.oracle.com/us/assets/hp07-oow17-promo-02-3737849.jpg"
}
Location
Represents a location object.
Name Description Type Required?
title The location title string No
url The URL for displaying the location on a map string No
latitude The GPS coordinate's longitude value double Yes
longitude The GPS coordinate's latitude value double Yes
For example:
{
    "title": "Oracle Headquarters",
    "url": "https://www.google.com.au/maps/place/37°31'47.3%22N+122°15'57.6%22W",
    "longitude": -122.265987,
    "latitude": 37.529818
}
Action
An action represents something that the user can select.
Name Description Type Required?
type The action type string Yes
label The descriptive label text for the action. string At least one of label or imageUrl will be present.
imageUrl The image for the action string At least one of label or imageUrl will be present.
PostbackAction
Sends a predefined postback back to the skill when the user selects an action.
Name Description Type Required?
type The action type "postback" Yes
postback The postback that's returned when the user selects an action. A string or JSON object Yes
For example:
{
    "type": "postback",
    "label": "Large Pizza",
    "imageUrl": "https://example.com/images/gallery/locations/11.jpg",
    "postback": {
        "state": "askSize",
        "action": "getCrust"
    }
}
CallAction
Requests the client to call a specified phone number on behalf of the user.
Name Description Type Required?
type The action type "call" Yes
phoneNumber The phone number to call string Yes
For example:
{
    "type": "call",
    "label": "Call Support",
    "imageUrl": "http://example.com.ar/files/2016/05/cuidado.jpg",
    "phoneNumber": "18005555555"
}
urlAction

Requests the client to open a website in a new tab or in an in-app browser.

Name Description Type Required?
type The action type "call" Yes
url The URL of the website that's displayed. string Yes
ShareAction
Requests the client to open a sharing dialog for the user.
Name Description Type Required?
type The action type "share" Yes
LocationAction
Requests the client to ask for the user's location.
Name Description Type Required?
type The action type "location" Yes
For example:
{
    "type": "location",
    "label": "Share location",
    "imageUrl": "http://images.example.com/location-clipart-location-pin-clipart-1.jpg"
}
Conversation Message
All of the messages that are part of a conversation have the following structure:
Name Description Type Required?
messagePayload The message payload Message Yes
userId The user ID string Yes
For example:
{
    "messagePayload": {
        "text": "show menu",
        "type": "text"
    },
    "userId": "guest"
}
Message
Message is an abstract base type for all other messages. All messages extend it to provide some information.
Name Description Type Required?
type The message type string Yes
User Message

Represents a message sent from the user to the skill.

User Text Message
The simple text message that's sent to the server.
Name Description Type Required
type The message type "text" Yes
text The message text string Yes
For example:
{
    "messagePayload": {
        "text": "Order Pizza",
        "type": "text"
    },
    "userId": "guest"
}
User Postback Message
The postback response message that's sent to the server.
Name Description Type Required
type The message type "postback" Yes
text The postback text string No
postback The postback of the selected action A string or JSON object Yes
For example:
{
    "messagePayload": {
        "postback": {
            "variables": {
                "pizza": "Small"
            },
            "system.botId": "69BBBBB-35BB-4BB-82BB-BBBB88B21",
            "system.state": "orderPizza"
        },
        "text": "Small",
        "type": "postback"
    },
    "userId": "guest"
}
User Attachment Message
The attachment response message that's sent to the server.
Name Description Type Required
type The message type "attachment" Yes
attachment The attachment metadata Attachment Yes
For example:
{
    "messagePayload": {
        "attachment": {
            "type": "image",
            "url": "http://oda-instance.com/attachment/v1/attachments/d43fd051-02cf-4c62-a422-313979eb9d55"
        },
        "type": "attachment"
    },
    "userId": "guest"
}
User Location Message
The location response message that's sent to the server.
Name Description Type Required
type The message type "location" Yes
location The user location information Location Yes
For example:
{
    "messagePayload": {
        "location": {
            "latitude": 45.9285271,
            "longitude": 132.6101925
        },
        "type": "location"
    },
    "userId": "guest"
}
Bot Message

Represents the message sent from the skill to the user.

Bot Text Message
Represents a text message.
Name Description Type Required
type The message type "text" Yes
text The message text string Yes
actions An array of actions related to the text. Array No
globalActions An array of global actions related to the text. Array No
For example:
{
    "messagePayload": {
        "type": "text",
        "text": "What do you want to do?",
        "actions": [
            {
                "type": "postback",
                "label": "Order Pizza",
                "postback": {
                    "state": "askAction",
                    "action": "orderPizza"
                }
            },
            {
                "type": "postback",
                "label": "Cancel A Previous Order",
                "postback": {
                    "state": "askAction",
                    "action": "cancelOrder"
                }
            }
        ]
    },
    "userId": "guest"
}
Bot Location Message
Represents a location message.
Name Description Type Required
type The message type "location" Yes
location The location Location Yes
actions An array of actions related to the text. Array No
globalActions An array of global actions related to the text. Array No
Bot Attachment Message
Represents an attachment message.
Name Description Type Required
type The message type "attachment" Yes
attachment The attachment sent Attachment Yes
actions An array of actions related to the text. Array No
globalActions An array of global actions related to the text. Array No
Bot Card Message
Represents a set of choices that are displayed for the user, either horizontally as carousels or vertically as lists.
Name Description Type Required
type The message type "card" Yes
layout Whether to display the messages horizontally or vertically. string (values: horizontal, vertical) Yes
cards An array of cards to be rendered. Array Yes
headerText The cards' header text string No
actions An array of actions related to the text. Array No
globalActions An array of global actions related to the text. Array No
Card
Represents a single card in the message payload.
Name Description Type Required?
title The title of the card, displayed as the first line on the card. string Yes
description The description of the card string No
imageUrl The URL of the image that is displayed. string No
url The website URL that's opened by a tap. string No
actions An array of actions related to the text array No
Here's an example:
{
    "messagePayload": {
        "type": "card",
        "layout": "horiztonal",
        "cards": [
            {
                "title": "Hawaiian Pizza",
                "description": "Ham and pineapple on thin crust",
                "actions": [
                    {
                        "type": "postback",
                        "label": "Order Small",
                        "postback": {
                            "state": "GetOrder",
                            "variables": {
                                "pizzaType": "hawaiian",
                                "pizzaCrust": "thin",
                                "pizzaSize": "small"
                            }
                        }
                    },
                    {
                        "type": "postback",
                        "label": "Order Large",
                        "postback": {
                            "state": "GetOrder",
                            "variables": {
                                "pizzaType": "hawaiian",
                                "pizzaCrust": "thin",
                                "pizzaSize": "large"
                            }
                        }
                    }
                ]
            },
            {
                "title": "Cheese Pizza",
                "description": "Cheese pizza (i.e. pizza with NO toppings) on thick crust",
                "actions": [
                    {
                        "type": "postback",
                        "label": "Order Small",
                        "postback": {
                            "state": "GetOrder",
                            "variables": {
                                "pizzaType": "cheese",
                                "pizzaCrust": "thick",
                                "pizzaSize": "small"
                            }
                        }
                    },
                    {
                        "type": "postback",
                        "label": "Order Large",
                        "postback": {
                            "state": "GetOrder",
                            "variables": {
                                "pizzaType": "cheese",
                                "pizzaCrust": "thick",
                                "pizzaSize": "large"
                            }
                        }
                    }
                ]
            }
        ],
        "globalActions": [
            {
                "type": "call",
                "label": "Call for Help",
                "phoneNumber": "123456789"
            }
        ]
    },
    "userId": "guest"
}
Bot Postback Message
Represents a postback.
Name Description Type Required
type The message type "postback" Yes
text The message text string No
postback The postback A string or a JSON object Yes
actions An array of actions that are related to the text Array No
globalActions An array of global actions related to the text Array No
Bot Raw Message
Used when a component creates the channel-specific payload itself.
Name Description Type Required?
type The message type "raw" Yes
payload The channel-specific payload A JSON object Yes

Embed Chat in Visual Builder Apps

Using the <oj-oda-chat> Web Component, you can embed chat in Oracle Visual Builder apps. This component, which is available from the Component Exchange that's associated with your instance, provides the following:
  • Support for System.CommonResponse component-based conversations
  • Speech integration
  • Attachment sharing
  • Connection to authentication-enabled channels
  • Audio response for skill messages
  • Delegate
  • Theming
Refer to the Oracle Visual Builder Documentation for information on adding components from the Component Exchange.

Tutorial: Access a Skill from Your Website

You can get a hands-on look at setting up the Oracle Web Channel, embedding the widget in a web page, customizing the widget's look and feel, and enabling autocomplete through this tutorial: Access a Skill from Your Website.

Oracle Web Channel Extensions

For Oracle Web channels, you can extend the functionality of System.CommonResponse components with capabilities that are specific to the JavaScript SDK.

You access the extensions by using the channelCustomProperties element in the System.CommonResponse component and setting the appropriate properties. The code has the following format:

...
            channelCustomProperties:
            - channel: "web"
              properties:
                PROPERTY_NAME: "PROPERTY_VALUE"
...

Here are the available custom properties for Oracle Web channels:

Name Allowed Values Applies To... Description
mediaType
  • A valid media type
  • Response items with the following attributes:
    • type: "attachment"
    • attachmentType: "file"or attachmentType: "image"
  • Cards with imageUrl specified
The media type of the attachment. For example, image/jpeg. If not specified, the media type will be resolved from the attachment URL.

For more general information on channelCustomProperties, see Channel-Specific Extensions.