Oracle Cloud Infrastructure Documentation

Oracle Web

The Digital Assistant Client SDK for Oracle Web enables you to run a skill in a web page. It also lets you customize the look and feel of the widget that runs the chat as well.

The SDK connects to the Oracle Chat and Attachment Handler server, which stands between Oracle Digital Assistant and the skill. 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.

Configure the Oracle Web Channel

You can configure the channel to connect to the Oracle Chat Server in two modes: authenticated 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.

  • Unauthenticated mode – Use the unauthenticated mode when the client can't generate signed JWT tokens because of static websites, 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.
      • 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 allowed domains to connect to the Chat Server.
    • 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 when configuring the HTML page to host the chat widget.
  5. Switch Channel Enabled to On.
  6. Route the channel to your skill or Digital Assistant.

Install the SDK

Install the SDK by updating the <script> tag in an HTML page with the code that we provide:
  1. Download the Oracle Web SDK v1.0 from Oracle Technology Network’s ODA and OMC download page.
  2. Save web-sdk.js 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 chatWidgetWebSettings = {
            URI: '<Server URI>',
            channelId: '<Channel ID>',
            userId: '<User ID>'
        };
        function initSdk(name) {
            // Default name is Bots
            if (!name) {
                name = 'Bots';
            }
            setTimeout(() => {
                window[name] = new WebSDK(chatWidgetSettings);  // Initiate library with configuration
                window[name].connect()                          // Connect to server
                    .then(() => {
                        console.log("Connection Successful");
                    })
                    .catch((reason) => {
                        console.log("Connection failed");
                        console.log(reason);
                    });
            });
        }
    </script>
    <script src="<WebSDK URL>" onload="initSdk('<WebSDK namespace>')">
  4. Define the following properties:
    • URI - The URI of the Oracle Chat and Attachment Handler 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>().
      (window, document, "./scripts/web-sdk.js", "Bots");
      To find out more about the APIs, refer to the SDK reference.

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 chatWidgetWebSettings = {
        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(() => {
            window[name] = new WebSDK(chatWidgetSettings, generateToken);   // Initiate library with configuration
            window[name].connect()                                          // Connect to server
                .then(() => {
                    console.log("Connection Successful");
                })
                .catch((reason) => {
                    console.log("Connection failed");
                    console.log(reason);
                });
        });
    }
</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.

Network Configuration

Use these properties to install the SDK.
Property Name Required? Default Value Description
URI Yes N/A The URL of the Oracle Chat and Attachment Handler Server
channelId Yes N/A The Channel ID of the Oracle Web Channel
userId No A randomly generated value A unique identifier for the user. If you don't provide this, Oracle Digital Asssistant generates one.
clientAuthEnabled Yes false 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.

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
For example:
     <script>
        var chatWidgetSettings = {
            URI: YOUR_URI,
            channelId: YOUR_CHANNELID,
            enableClearMessage: true,
            enableLocalConversationHistory: true,
            enableTimestamp: true,
            showConnectionStatus: true,
            showTypingIndicator: true,
            disablePastActions: 'all',
...
         };

...
    </script>
Property Name Required? Default Value Description
displayActionsAsPills No false Displays pill-shaped action buttons.
enableAttachment No true Configures attachment sharing.
enableBotAudioResponse No false Configures the skill responses. The skill responses are read aloud the Web API.
enableClearMessage No false Enables the clear message button in the chat widget header.
enableLocalConversationHistory No false Enables the previous conversation that's associated with a given userId to be loaded in the browser when the widget has been initialized.
enableSecureConnection No true Configures secure communication (https v. http and wss v. ws).
enableTimestamp No true Enables the "read" timestamp for messages.
openChatOnLoad No false Expands the chat widget when the page is loaded.
showConnectionStatus No false Enables the connection status to display in the chat widget header.
showTypingIndicator No true Displays a chat bubble when waiting for a response.
disablePastActions Yes all Disables the button clicks on the messages that users have already interacted with. The allowed values are all, none, or postback.

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.
Property Name Required? Default Value Description
customHeaderElementId No N/A The id of the <div> element that's added to the header of the chat widget. Used for additional elements in the chat widget header.
delegate No N/A An object that sets a delegate to receive callbacks before certain events occur in a conversation.
targetElement No widgetDiv The div element at which the chat widget gets embedded.
embeddedVideo No false Enables the embedding of a YouTube video link in a text message.
embedTopStickyId No N/A The ID of the element used for the sticky content that appears at the top of the chat. Use this property to add custom content in the chat widget's conversation view. See Non-Scrolling Content: Example.
embedBottomScrollId No N/A 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.
embedBottomStickyId No N/A 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.
isDebugMode No false Enables debug mode.
initUserHiddenMessage No N/A A user text message that's used to initiate a conversation. This message, which is sent when chat widget is ready, does not actually display in chat. For example: initUserHiddenMessage: 'Hi'
i18n No {'en-us':{…}} An object that contains locale fields. Each locale maintains i18n key-value pairs for the text strings used in the widget.
locale No en-us The skill's default locale for text. The browser's il8n translations are used instead of the skill's when they're available. Otherwise, the translations for the skill's location are used.
messageCacheSizeLimit No 2000 The maximum number of messages that get save in localStorage at a time.
readMark No ¿ A symbol for read messages, which is disabled when enableTimestamp is set to false.

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 Required Default Value Description
badgePosition No {"top": "0", "right": "0"} The position of the badge icon with respect to the icon button.
colors No {"branding": "#1B8FD2", "text": "#212121", "textLight": "#737373"} The colors used in the chat widget.
conversationBeginPosition No top 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.
font No 16px "Helvetica Neue", Helvetica, Arial, sans-serif The font used in the chat widget.
height No 70vh The height of a chat width as set by one of the <length> data type values.
messagePadding No 15px The padding around messages in the chat widget.
position No {bottom: '20px', right: '20px'} The placement of the chat widget in the browser window. This should be passed as a JSON object.
width No 30vw The width of the chat widget as set to one of the <length> data type values.

Custom Icons

You can create customizations the various icons, including the ones for the skill icon, the chat logo icon, and the avatar icons for the skill and user. For example:
   <script>
    var chatWidgetWebSettings = {
        URI: YOUR_URI,
        channelId: YOUR_CHANNELID,
        font: '14px "Helvetica Neue", Helvetica, Arial, sans-serif',
        height: '60vh',
        width: '20vw',
         "colors":{
            "branding": "#01538A",
            "text": "#B20637",
    },
    botButtonIcon: 'images/Robot.png',
    logoIcon: 'images/logo.png',
    botIcon: 'images/Robot.png',
    personIcon: 'images/userIcon.png',
    locale: 'en-us', 
    i18n: {
      
        "en-us":{
        "chatTitle": "Support"
        }
    }
    };
...
</script>
Property Required? Default Value Description
botButtonIcon No N/A the image URL for the skill button
logoIcon No N/A The image URL for the skill logo, which is displayed in the header of the widget.
botIcon No N/A The image URL of the image that depicts the skill (an avatar?) that displays beside the skill responses. This icon only displays when you define this property.
personIcon No N/A The URL of the image that depicts the user (and displays beside the user's responses). This image only displays when you define this icon.
chatBubbleIcon No N/A The URL for the image of the chat bubble icon.
chatBubbleIconHeight No 42px The height of the loading chat bubble icon.
chatBubbleIconWidth No 56px The width of the loading chat bubble icon.
audioIcon No N/A The URL of the image icon for an image type of attachment, which is displayed when the attachment source URL can't be reached.
fileIcon No N/A The image URL for a file type attachment.
imageIcon No N/A The image URL for a video type attachment which is displayed when the source URL can't be reached.
videoIcon No N/A The URL for the video attachment type, which is displayed when the source URL can't be reached.
sendIcon No N/A The URL for the image used for the send icon.
errorIcon No N/A The URL for the image used for the error icon.

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"
}
Key Default Value Description
branding #1B8FD2 The primary color for the widget branding. The color used as the header background and as the hover color on footer buttons.
text #212121 The text color for messages in the chat widget.
textLight #737373 The text color of secondary text in messages (such as the card descriptions in the chat widget).

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, the en-us translations are displayed for the missing values.
"i18n": {
    "fr": {
        "chatTitle": "Soutien"
    },
    "en-us": {
        "chatTitle": "Support"
    },
    "es": {
        "chatTitle": "Apoyo"
    },
    "zh-cn": {
        "chatTitle": "¿¿"
    }
}
Key Default Value Description
audioResponseOff Audio response off The tooltip that appears when the user hovers over an audio utterance "on" button in header.
audioResponseOn Audio response on The tooltip that appears when the user hovers over the audio utterance "off" button in header.
cardImagePlaceholder Loading image The placeholder text that displays while the card image is fetched and loaded.
chatTitle Ask The title of the chat widget that is displayed in the header.
clear Clear The tooltip that appears when the user hovers over the Clear Messages button in the header.
close Close The tooltip that appears when the user hovers over the close widget button in the header.
closing Closing The status text that displays while the connection between chat widget and server is closing.
connected Connected The status text that displays while the connection between chat widget and server is established.
connecting Connecting The status text that displays when the chat widget connects to the chat server.
disconnected Disconnected The status text that displays when the connection between chat widget and server has closed.
inputPlaceholder Type a message The placeholder text that appears in the user input field.
previousChats Previous conversations The status text that displays at the end of older messages.
requestLocation Requesting location The text that displays while the user location is requested.
requestLocationString Cannot access your location. Please allow access to proceed further. The error text that displays when the user denies the location request.
retryMessage Try again The text that displays when the user message has not been sent to the server.
send Send The tooltip appears when the user hovers over the send button in the footer.
upload Upload Document The tooltip that appears when the user hovers over the upload button in the footer.
uploadFailed Upload Failed. The error text that displays when an upload fails.
uploadFileSizeLimitExceeded Upload Failed. File size should not be more than 15MB. The error text that displays when the size of the upload file exceeds the limit.
uploadUnsupportedFileType Upload Failed. Unsupported file type. The error text that displays when an upload is attempted for an unsupported file type.

Embed the Widget in the Web Page

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.

Non-Scrolling Content: Example

In the following example, the customHeaderElementId and embedTopStickId properties reference the IDs of the DOM element that define the stationary text.
<head>
     <script>
        var chatWidgetSettings = {
            URI: YOUR_URI,
            channelId: YOUR_CHANNELID,
            enableClearMessage: true,
            enableLocalConversationHistory: true,
            enableTimestamp: true,
            showConnectionStatus: true,
            showTypingIndicator: true,
            disablePastActions: 'all',
            customHeaderElementId: "customHeaderElement",
            embedTopStickyId: "topStickyElement",
            isDebugMode: true,
            locale: 'en-us',
            "i18n": {
                "en-us": {
                    "chatTitle": "Pizza King"
                }
            }  
         };
...
    </script>
</head>

<body>
    
    <div id="customHeaderElement"><b>Always Fresh!</b></div>
        <div id="topStickyElement"><p style="border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">There’s no better feeling in the world than a warm pizza box on your lap.</p></div>
    <h3 align="center">This is a sample page having ODA web widget built using Oracle Web SDK</h3>
</body>