37 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 ODA speech, text, or attachment server in two modes: authenticated (to protect access to the channel) or unauthenticated.
  • Authentication is enforced using JSON Web Tokens (JWT). The customer's backend server generates the JWT token, which is then passed to the Oracle Web SDK. This token is used for each request to an ODA speech, text, or attachment server.

    Note:

    To protect access to the channel, the token must always be generated by a remote server. It must never be generated within the client browser.
    When the web app needs to connect to an ODA server, it first requests the token from the backend server and then adds it to the Authorization header. The ODA server validates the token, evaluates the claims, and then either opens the socket or rejects the connection.

    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 a client authentication-enabled channel.
      • The channel will only communicate with the sites from the domains that you add as a comma-separated list. For example, *.corp.example.com, *.hdr.example.com. Entering a single asterisk (*) allows unrestricted access to the channel from any domain. Typically, you'd only enter a single asterisk during development. For production, you would add an allowlist of domains.
      • 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 comma-separated list of domains that can access the channel. If the domains in this allowlist includes asterisks (*.hdr.example.com) or if the allowlist is not completely known, then you might consider an authenticated connection.
    • 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 these 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.

Tutorial: Secure Your Oracle Web SDK Chat

You can get a hands-on look at securing the Web chat widget through this tutorial: Secure Your Oracle Web SDK Chat.

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 in the Oracle Web SDK ZIP file.

Import the Library Using the Asynchronous Module Definition API

You can import the library using implementations of the Asychronous Module Definition (AMD) API such as RequireJS with Oracle JET, and SystemJS.
requirejs(['<path of the web-sdk>'], function(WebSDK) {
    const settings = {
        URI: '<Server URI>',
        channelId: '<Channel ID>',
        userId: '<User ID>'
    };
    Bots = new WebSDK(settings);
 
    Bots.connect();
});

Import the Library Dynamically with JavaScript

Use the following Mozilla Development Network (MDN)-based utility function to import the library dynamically with JavaScript:
function fetchSDK(src, onloadFunction) {
    const script = document.createElement('script');
    script.type = 'application/javascript';
    script.async = true;    // load the script asynchronously
    script.defer = true;    // fallback support for browsers that does not support async
    script.onload = onloadFunction;
    document.head.appendChild(script);
    script.src = src;
}
 
fetchSDK('<path of the web-sdk>', initSdk);

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 to the .
  • 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 and 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 token header looks something like this:
    {
    
     "alg": "HS256",
    
     "typ": "JWT"
    
    }
    An example token 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 using the 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. This setting applies to all links present in the conversation, including action buttons, fallback links for attachments, and card links. 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
initMessageOptions Sends messages as soon as the client has connected to the skill, regardless of whether the widget is expanded or not. This setting accepts an object containing a sendAt property. The sendAt property can have one of the two values: 'init', or 'expand'. If you set 'init', then the init messages are sent as soon as connection is made. If you set 'expand', then the init messages are sent only when the widget is expanded. For example, to send the hidden message as soon as the connection is established:
var settings = {
    URI: '...',
    channelId: '...',
    initUserHiddenMessage: 'Hello',
    initMessageOptions: {
        sendAt: 'init'
    }
}
Bots = new WebSDK(settings);
Bots.connect();
Billing starts when the init message has been sent, even if the widget is still closed.
   
initUserHiddenMessage A message that's used to initiate a conversation. This message, can be a text string or a message payload. For example: initUserHiddenMessage: 'Hi'. These messages are not dependent on the user history. They are sent in every session after the client has connected to the skill and the chat widget has opened. To send the first message only when the conversation history is empty, you must bind event listeners using the Bots.on() method. For example, you can accomplish this by binding the WIDGET_OPENED and NETWORK events, which are described in the SDK docs. 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." These messages are sent after the client has connected to the skill and the chat widget is expanded.
No N/A
isDebugMode Enables debug mode. No false
linkHandler An object that overrides the configuration for handling the clicks on the links that are embedded in the skill's responses. There are two ways that this object handles links: target, which accepts a string, and onclick, which accepts a function. You can set either target or onclick, but not both. No
{ onclick: <function>, target: 'string' }
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 (
'✓'
)
shareMenuItems The menu items in the share popup menu. This property accepts an array with string values that are mapped to menu items:
  • 'visual' for image and videos
  • 'audio' for audio
  • 'file' for files
  • 'location' for location
You can specify which items are available in the menu (['audio', 'file'], for example). All of the menu items are available when the array is empty, when the items in the array are incorrect (['audio', 'visuil'], or when shareMenuItems has not been defined.
No
['audio', 'file', 'location', 'visual']
skillVoices The expected locale of the user's speech that's used for voice recognition. The supported locales are: French ('fr-fr'), Spanish ('es-es'), and the default, English ('en-US'). The speech locale can be set dynamically by calling the setSpeechLocale('<locale>') API. Voice recognition will not work if an unsupported locale has been passed. No 'en-us'
speechLocale The expected locale of the user's speech that's used for voice recognition. The supported locales are: French ('fr-fr'), Spanish ('es-es'), and the default, English ('en-US'). The speech locale can be set dynamically by calling the setSpeechLocale('<locale>') API. Voice recognition will not work if an unsupported locale has been passed. No 'en-us'
storageType The web storage mechanism that's used to store the conversation history for users whose userId is passed by the host app. The supported values are 'localStorage' and 'sessionStorage'. Anonymous users’ conversations are always stored in sessionStorage and are deleted automatically after the browser session has ended. No 'localStorage'
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':
        <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 N/A
theme The primary layout theme. Three themes are available: 'default', 'redwood-dark', and 'classic'. No default
timestampFormat Formats the delivery timestamp that accompanies messages. Accepts values in a DateTimeFormat options object or as a pattern string as described in Customize the Timestamp. No
{
weekday:'long',
year:'numeric',
month: 'long',
day: 'numeric'

}
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'}
theme The primary layout theme. The valid values are 'default', 'redwood-dark', and 'classic'. No 'default'
width The width of the chat widget as set to one of the <length> data type values. No 30vw

Custom Header Button Icons

You can customize the header's clear message This is am image of the clear messages icon., audio response toggle button This is an image of the Audio Response icon., and the close button This is an image of the Close icon. in two ways: by passing the source URL of the image, or by passing a raw SVG string. For raw SVG strings, the fill color of the SVG can be customized by CSS classes, as well as by passing a color value in the colors.headerButtonFill property in the initial settings.

Note:

The color customization may not work for all SVGs, as they can be multi-colored or have their own stroke and fill colors.
Icon Function Feature Flag Customization
Clear Message Clears both the current and older messages in the conversation. enableClearMessage: true '<image URL | SVG string>'
Audio response Toggles the audio of skill responses as they are received. Because this a toggle button, it has two states, utterance on, where responses are spoken, and utterance off, where responses are not spoken. enableBotAudioResponse: true
  • Response on: audioResponseOnIcon: '<image URL | SVG string>'
  • Response off: audioResponseOffIcon: '<image URL | SVG string>
Close Collapses the widget and displays the launch button This is an image of the launch icon.. This button cannot be disabled. None: This icon is always enabled in the chat widget. It's not displayed in the embedded mode. closeIcon : '<image URL | SVG string>'

Custom Colors

You can customize the widget's colors. As illustrated by the following snippet, you use hexadecimal colors to define the strings.
"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
actionsBackground The background color for the action buttons
actionsBackgroundFocus The background color for the action buttons when they're in focus.
actionsBackgroundHover The background color of the action buttons on hover
actionsBorder The border color for the action buttons
actionsText The text color for the action buttons
actionsTextFocus The text color for the action buttons on focus
actionsTextHover The text color for the action buttons on hover
botMessageBackground The color for the background of the skill's response message bubble
botText The color for the text in a message sent by the skill
branding The primary color for the widget branding. This color is used as the header background and as the hover color on footer buttons.
cardBackground The background color used for a card.
conversationBackground The color used for the background of the conversation pane.
footerBackground The color used for the backgound of the footer.
footerButtonFill The fill color of an SVG icon used in the buttons that are located in the chat footer.
globalActionsBackground The background color of the global action buttons
globalActionsBackgroundFocus The background color of the global action buttons when they're in focus.
globalActionsBackgroundHover The background color for the hover over the global action buttons.
globalActionsBorder The border color of the global action buttons
globalActionsText The text color of the global action buttons
globalActionsTextFocus The color of the text in the global action buttons when they're in focus.
globalActionsTextHover The color of the text in the global action buttons when users hover over them.
headerBackground The background color of the chat widget’s header
headerButtonFill The fill color of the SVG icons used for the buttons in the chat header
headerText The color of the chat header title
inputBackground The message input field background color in the chat footer
inputText The message input text color in the chat footer
links The color for links in messages
notificationBadgeBackground The background color for the message notification badge
notificationBadgeText The text color for the message count in the notification badge
recognitionViewBackground The background color for the view where the recognized text displays when users activate the voice mode. If you don't define this color, then the color defined for headerBackground is used instead.
recognitionViewButtonFill The SVG fill color for the voice-text mode toggle when users switch to the voice mode.
recognitionViewText The color used for the text that's recognized from the user's voice input. If you don't define this color, then color defined for text is used instead.
text The text color for messages in the chat widget.
textLight The text color of the secondary text in the messages, such as the card descriptions in the chat widget.
typingIndicator The background fill color used for the typing indicator.
userMessageBackgound The background color of the bubble used for user messages.
userText The color for the text in a message sent by the user.
visualizer The color used for the bars in the visualizer graph. If you don't define this color, then the color defined for branding is used instead.
visualizerContainerBackground The background color for the container of the voice visualizer that displays when users toggle to the voice mode. If you don't define this color, then the color defined for userMessageBackgound is used instead.

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: 'https://image.flaticon.com/icons/svg/3011/3011301.svg',
    personIcon: 'https://image.flaticon.com/icons/svg/3011/3011311.svg',
    
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>'
};
You can pass the raw SVG data for icons that support SVG strings. The chat view renders these as an inline SVG.

Tip:

SVG strings load faster than image assets. They also let you animate the image and change its color. The layout defined for the theme property is applied to SVG strings for attachment, send, and mic buttons, but not for the other image assets.
Property Description SVG String Compatible?
agentAvatar For skills integrated with live agents, this icon displays alongside messages from the live agent. The botIcon appears if this property is not defined. Yes
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. Yes
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
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
keyboardIcon The keyboard icon, displayed in button that switches the mode from voice to keyboard mode. Yes
imageIcon The image attachment icon, which is displayed when the attachment source cannot be reached. No
logoIcon The chat logo icon which is displayed in the header of the chat widget. No
micIcon The mic button icon Yes
personIcon The icon that displays alongside user messages. The person icon does not display be default: it only displays if you define it. 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 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
attachmentAudioFallback The fallback message that is displayed in place of an audio attachment if the audio can not be rendered by the client. The text between {0} and {/0} is set to a link to download the file. Your browser does not support embedded audio. However you can {0}download it{/0}.
attachmentVideoFallback The fallback message that is displayed in place of an video attachment if the video can not be rendered by the client. The text between {0} and {/0} is set to a link to download the file. Your browser does not support embedded video. However you can {0}download it{/0}.
audioResponseOff The tooltip that appears when the user hovers over an audio utterance on button in header. Turn audio response off
cardImagePlaceholder The placeholder text that displays while the card image is fetched and loaded. Loading image
audioResponseOn The tooltip that appears when the user hovers over the audio utterance "off" button in header. Turn audio response on
card The identifier for the card Card
cardNavNext The label for the card navigation button for displaying the next card in a horizontal layout. Next card
cardNavPrevious The label for the card navigation button for displaying the previoust card in a horizontal layout. Previous card
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
errorSpeechUnsupportedLocale The error message that's displayed when a recording is attempted and an unsupported locale has been configured for voice recognition. The set speech locale is not supported. Cannot start recording.
errorSpeechInvalidUrl The error message that's displayed when the speech server URL is not set.  
errorSpeechMultipleConnection The error message that's displayed when multiple speech connections are attempted wihtin a short interval.  
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.
openMap The label for the action button that's used to open a location map. Open Map
previousChats The status text that displays at the end of older messages. Previous conversations
recognitionTextPlaceholder The placeholder text that's displayed in the recognition text view.  
requestLocationDeniedPermission The error message that's displayed when the permission to access location is denied. Location permission denied. Please allow access to share your location, or else type in your location.
requestLocationDeniedTimeout The error message that's displayed when the location request is not resolved because of a timeout. Taking too long to get your current location. Please try again, or else type in your location.
requestLocationDeniedUnavailable The error message displayed when the location request is denied because the current location of the client device is unavailable. Your current location is unavailable. Please try again, or else type in your location.
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
shareAudio The menu item text in the share the popup for sharing an audio file Share Audio
shareFailureMessage The error message that's displayed when the share action button in a message is clicked, but the share API is unavailable in the client device, or the share request has been rejected. Sorry, sharing is not available on this device.
shareFile The menu item text in the share popup for sharing a generic file Share File
shareLocation The menu item text for sharing a location in the popup Share Location
shareVisual The menu item text in the share popup for sharing an image or video file Share Image/Video
skillMessage A skill message indicator for screen readers. It's spoken by the screen readers before the skill responses. Skill says
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. Share popup
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.
userMessage A user message indicator for screen readers. It's spoken by the screen readers before the user messages. I say
utteranceGeneric The fallback description for the response message that's used in utterance Message from skill.

Configure Share Menu Options

By default, the share menu displays options for the following file types:
  • visual media files (images and videos)
  • audio files
  • general files like documents, PDFs, and spreadsheets
  • location


The shareMenuItems setting allows you to restrict the items that display in the share menu. The setting accepts a string array with keys that are mapped to the share menu items: 'visual' for the Share Image/Video item, 'audio' for the Share Audio item, 'file' for the Share File item, and 'location' for the Share Location item. You can use these keys, which are not case-sensitive, to specify which items are available in the menu (['visual', 'location'], for example). All of the menu items are available when the array is empty, or when an invalid value is passed.

Note:

You can disable the attachment functionality by setting enableAttachment to false.


Using attachment functionality often requires updating the network security policy of the host site. The attachments, which are uploaded to Oracle Digitial Assistant object storage using HTTP calls, may get blocked by the site's CORS policies. With the site blocking the uploads, an error can display in the browser console indicating that the client has blocked the request because of a CORS policy. To fix such issues, the network security policy of the host site should be updated to allow the Oracle Digital Assistant domain. This allows the upload requests to go through. Since the CORS policy does not apply to WebSockets, the conversations between the SDK and the skills are not impacted by such restrictions.

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-button The collapsed chat component button
oda-chat-button-clear The clear messages button
oda-chat-button-close The close widget button
oda-chat-button-narration The skill's audio response toggle button
oda-chat-button-send The send message button
oda-chat-button-upload The upload file button
oda-chat-card The card message
oda-chat-closing Applied as a sibling to oda-chat-connection-status when the widget is disconnecting from server
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-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-conversation The container for the conversation
oda-chat-disconnected Applied as a sibling to oda-chat-connection-status when the widget is disconnected from server
oda-chat-footer The chat widget footer
oda-chat-footer-button The common class for all footer buttons
oda-chat-header The chat widget header
oda-chat-header-button The common class for all header buttons
oda-chat-icon-wrapper The wrapper for the skill or for a person that's displayed alongside the message.
oda-chat-left The wrapper for the skill message
oda-chat-logo The logo on the widget header
oda-chat-message The common wrapper class for all chat messages
oda-chat-message-action-location The location request action button
oda-chat-message-action-postback The postback action button
oda-chat-message-actions The action buttons wrapper
oda-chat-message-bubble The message bubble
oda-chat-message-global-actions The global action buttons wrapper
oda-chat-message-icon The image for the skill or for a person that's displayed alongside the message.
oda-chat-notification-badge The notification badge for messages that haven't been viewed.
oda-chat-right The wrapper for the user message
oda-chat-title The title on the widget header
oda-chat-user-input The user input text area
oda-chat-widget The expanded chat component, which wraps the widget header, conversation, and footer.
oda-chat-wrapper The wrapper for entire chat component

Customize the Timestamp

By default, the timestamp that displays in the header when enableTimestampdates is set to true displays the format as the locale's day of the week, month, date, year, and time (am and pm). For example, Thursday, August 13, 2020, 9:52:22 AM. You can configure this timestamp by passing formatting options in the timestampFormat setting. You can format the timestamp by either passing a pattern string of formatting tokens, or by passing an object containing Intl.DateTimeFormat options.

Format the Date-Time with Pattern Strings
The pattern strings used for formatting the timestamp are made up of format tokens. For example, passing timestampFormat: 'hh:mm:ss a' sets the timestamp as 09:30:14 pm.

Note:

These tokens are case-sensitive, so for example, passing yyyy instead of YYYY would prevent the year from displaying.
Component Token Output
Day of the month
  • D
  • Do
  • DD
  • 1 2 ... 30 31
  • 1st 2nd ... 30th 31st
  • 01 02 ... 30 31
Day of the week
  • d
  • dd
  • dddd
  • 0 1 ... 5 6
  • Sun Mon ... Fri Sat
  • Sunday Monday ... Friday Saturday
Month
  • M
  • MM
  • MMM
  • MMMM
  • 1 2 ... 11 12
  • 01 02 ... 11 12
  • Jan Feb ... Nov Dec
  • January February ... November December
Year
  • YY
  • YYYY
  • 70 71 ... 29 30
  • 1970 1971 ... 2029 2030
Hour
  • H
  • HH
  • h
  • hh
  • 0 1 ... 22 23
  • 00 01 ... 22 23
  • 1 2 ... 11 12
  • 01 02 ... 11 12
Minute
  • m
  • mm
  • 0 1 ... 58 59
  • 00 01 ... 58 59
Second
  • s
  • ss
  • 0 1 ... 58 59
  • 00 01 ... 58 59
Fractional Second
  • S
  • SS
  • SSS
  • 0 1 ... 8 9
  • 0 1 ... 98 99
  • 0 1 ... 998 999
AM/PM
  • A
  • a
  • AM PM
  • am pm
Timezone
  • Z
  • ZZ
  • -07:00 -06:00 ... +06:00 +07:00
  • -0700 -0600 ... +0600 +0700li
Format the Timestamp with Intl.DateTimeFormat Objects
The timestamp can also be formatted using the options defined for Intl.DateTimeFormat object. The properties that are passed with the object include:
Property Values
dateStyle 'full' | 'long' | 'medium' | 'short'
timeStyle 'full' | 'long' | 'medium' | 'short'
weekday
  • 'long' (for example, Thursday)
  • 'short' (for example, Thu)
  • 'narrow' (for example, T)
day
  • 'numeric'
  • '2-digit'
month
  • 'numeric' (for example, 2)
  • '2-digit' (for example, 02)
  • 'long' (for example, March)
  • 'short' (for example, Mar)
  • 'narrow' (for example, M)
year
  • 'numeric'
  • '2-digit'
era
  • 'long' (for example, Anno Domini)
  • 'short' (for example, AD)
  • 'narrow' (for example, A)
hour
  • 'numeric'
  • '2-digit'
minute
  • 'numeric'
  • '2-digit'
second
  • 'numeric'
  • '2-digit'
timeZoneName
  • 'long' (for example, British Summer Time)
  • 'short' (for example, GMT+1)
timeZone The time zone. All implementations must recognize UTC. The default value is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as Asia/Shanghai, Asia/Kolkata, America/New_York.
hour12 Whether to use 12-hour time (as opposed to 24-hour time). Values are true and false.

Send the Initial Message when the Conversation History is Empty

The initUserHiddenMessage messages are sent regardless of the user's conversation history; they are sent the first time the chat widget is opened for every session. To send the initial message when the conversation history is empty, you need to bind an event listener to the Bots.on() method. For example:
Bots = new WebSDK(chatWidgetSettings);

var isHandled = false;
var message = ;

Bots.on(WebSDK.EVENT.WIDGET_OPENED, function() {
    if (!isHandled && Bots.isConnected() && !Bots.getConversationHistory().messagesCount) {
        Bots.sendMessage(message, { hidden: true });
        isHandled = true;
    }
});

Bots.on(WebSDK.EVENT.NETWORK, function(state) {
    if (!isHandled && Bots.isConnected() && Bots.isChatOpened() && !Bots.getConversationHistory().messagesCount) {
        Bots.sendMessage(message, { hidden: true });
        isHandled = true;
    }
});

Bots.connect();

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
Description of the illustration autocomplete_phrase_list.png

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.

Avatars
By default, none of the messages in the chat are accompanied with avatars. Using the following parameters, however, you can configure avatars for the skill, the user, and an agent avatar when the skill is integrated with live agent support.
  • botIcon - The URL of the image that displays alongside the skill messages. For example: botIcon: 'https://image.flaticon.com/icons/svg/3011/3011301.svg'
  • personIcon - The URL of the image that displays alongside the user messages,. For example: personIcon: 'https://image.flaticon.com/icons/svg/3011/3011311.svg'
  • agentAvatar - URL of the image that displays alongside the agent messages. If you don't provide this value, but have defined botIcon, then the skill icon acts as the fallback and accompanies the agent's messages.

Note:

These settings can only be passed in the initialization settings. They cannot be modified dynamically.
Control Embedded Link Behavior

In addition to opening links within a new window by setting openLinksInNewWindow: true, or the default behavior of opening links in a new tab when this option is set to false, you can also open links which overlay the widget’s web page. To enable this and other overrides to the linking behavior, initialize the SDK with
linkHandler: {
    target: '_blank',   // open link in a new page
    onclick: (event) => { // some operation }
}
Use linkHander to:
  • Control iframe navigation so that it can continue to overlay the page without having to include the widget in every page, reopening it upon navigation, and maintaining the same user ID.

  • Open some links in a new window, while opening others in the same tab.
  • Performing an action when a link is clicked.
  • Preventing a link from opening.
To override the linking behavior set by the openLinksInNewWindow setting, you must define one, or both, of these attributes:
  • target – Names the browsing location context, such as tab, a window, or an iFrame. Define the iFrame location as the target attribute of an anchor element (<a>). You can define the target’s _self, _blank, _parent and _top attributes.
  • onclick - Accepts a callback function that is called when the link is clicked. The callback is passed the MouseEvent that's received on the click, and can be used to perform an action, or even prevent the link from opening.
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: function(message) {
        return message;
    },
    beforeSend: function(message) {
        return message;
    },
    beforePostbackSend: function(postback) {
        return postback;
    }
}

Bots.setDelegate(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.

Dynamic Typing Indicator

A typing indicator tells users to hold off on sending a message because the skill is preparing a response. By default, skills display the typing indicator only for their first response when you initialize the SDK with showTypingIndicator: 'true'. For an optimal user experience, the skill should have a dynamic typing indicator, which is a typing indicator that displays after each skill response. Besides making users aware the skill has not timed out but is still actively working on a response, displaying the typing indicator after each skill response ensures that users won’t attempt to send messages prematurely, as might be the case when the keepTurn property directs the skill to reply with a series of separate messages that don’t allow user to interject a response.

To enable a typing indicator after each skill response:
  • Initialize the SDK with showTypingIndicator set to true.
  • Call the showTypingIndicator API
The showTypingIndicator can only enable the display of the dynamic typing indicator when:
  • The widget is connected to the Oracle Chat Server. The dynamic typing indicator will not appear when the connection is closed.
  • The SDK has been initialized with showTypingIndicator set to true.

    Note:

    This API cannot work when the SDK is used in headless mode.
The typing indicator displays for the duration set by the optional property, typingIndicatorTimeout, that has default setting of 20 seconds. If the API is called while a typing indicator is already displaying, then the timer is reset and the indicator is hidden.

The typing indicator disappears as soon as the user receives the skill’s messages. The typing indicator moves to the bottom of the chat window if a user enters a message, or uploads an attachment, or sends a location, while it’s displaying.

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
    • Return suggestions for a query – Returns a Promise that resolves to the suggestions for the given query string. The Promise is rejected if it takes too long (which is approximately 10 seconds) to fetch the suggestion.
      Bots.getSuggestions(utterance)
          .then((suggestions) => {
              const suggestionString = suggestions.toString();
              console.log('The suggestions are: ', suggestionString);
          })
          .catch((reason) => {
              console.log('Suggestion request failed', reason);
          });

    Note:

    To use this API, you need to enable autocomplete (
    enableAutocomplete: true
    ) and configure autocomplete for the intents.
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.

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.

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.

Voice Visualizer

The chat widget displays a voice visualizer when users click the voice icon This is an image of the Voice Visualizer's Speak icon., the chat widget displays a voice visualizer. It's an indicator of whether the audio level is sufficiently high enough for the SDK to capture the user’s voice. The user’s message, as it is recognized as text, displays below the visualizer.

Note:

Voice mode is indicated when the keyboard This is an image of the keyboard icon. icon appears.
Description of voice_visualizer.png follows
Description of the illustration voice_visualizer.png
Because of the default setting for enableSpeachAutosend is true (enableSpeechAutoSend: true), messages are sent automatically after they're recognized. Setting enableSpeechAutoSend: false switches the input mode to text after the voice message is recognized, allowing users to edit or complete their messages using text before sending them manually. Alternatively, users can complete their message with voice through a subsequent click of the voice icon before sending them manually.

Note:

The voice visualizer is created using AnalyserNode. You can implement the voice visualizer in headless mode using the startVoiceRecording method. Refer to the SDK to find out more about AnalyserNode and frequency levels.

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

Note:

File uploads from the host site may fail and throw a console error similar to the following:
https://<oda-instance>/chat/v1/attachments from origin <client site> has been blocked by CORS policy: No Access-Control-Allow-Origin header is present on the requested resource
This is because the host site's CORS (Cross-Origin Resource Sharing) settings, which block all cross-origin HTTP requests, may also block upload requests from the client instance to the Oracle Digital Assistant attachment server. If you run into this problem, update the host site's security policy to allow the domain for the Digital Assistant instance. Because the conversation uses WebSocket connections, CORS does not impact the conversation.
Passing File Names
Use the following headers to retrieve the name of a file (including video, audio, or image files) that's uploaded to the ODA file server:
  • x-oda-meta-file-name
  • x-oda-meta-file-type
You can return these headers with GET or HEAD requests. Use HEAD if a custom component doesn't need the file's contents.
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: "websdk"
              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.