JavaScript SDK Reference for Oracle Digital Assistant
Release 19.1.5
F16196-04
Use the JavaScript SDK to add live messaging to your web site or web app.
Download the SDK
Download bots-client-sdk-js-19.1.5.0.zip
from the Oracle
Technology Network’s ODA downloads page.
Configuration
To improve performance, the Bots library, which is composed of multiple resources, is fetched at runtime. For that reason, the URL where the library's static files are hosted (that is, the public path), is hard-coded in many places.
To configure the library for your environment, run:
./configure <new-public-path>
The script will generate a folder with the configured project in it.
Examples
Local Testing Setup
- The static files are hosted at
http://localhost:8000/static/
. - The script is run in the
/home/your-name/
folder. For example:./configure http://localhost:8000/static/
The files will be available at /home/your-name/http:__localhost:8000_static_/
.
Production Setup
- The static files are hosted at
https://cdn.acme.org/
- The script is run in the /home/your-name/ folder. For example:
/configure https://cdn.acme.org/
The Files will be available at /home/your-name/https:__cdn.acme.org_/
.
Deployment
- Put all of the files from the generated folder at the root of the
storage after
https://placeholder.public.path/
.
For example, if your files are hosted athttp://localhost:8000/static/
, copy all the files to thestatic
folder on your local server. - If your storage is behind a CDN, make sure to issue a cache
invalidation for
https://placeholder.public.path/loccurredson
. - Make sure your server allows CORS requests.
- Test your deployment by initializing the SDK.
Usage
Script Tag
Add the following code towards the end of the head
section on your page and replace <sdk-folder-url>
with the URL where the SDK is hosted.
<script>
!function(e,t,n,r){
function s(){try{var e;if((e="string"==typeof this.response?JSON.parse(this.response):this.response).url){var n=t.getElementsByTagName("script")[0],r=t.createElement("script");r.async=!0,r.src=e.url,n.parentNode.insertBefore(r,n)}}catch(e){}}var o,p,a,i=[],c=[];e[n]={init:function(){o=arguments;var e={then:function(t){return c.push({type:"t",next:t}),e},catch:function(t){return c.push({type:"c",next:t}),e}};return e},on:function(){i.push(arguments)},render:function(){p=arguments},destroy:function(){a=arguments}},e.__onWebMessengerHostReady__=function(t){if(delete e.__onWebMessengerHostReady__,e[n]=t,o)for(var r=t.init.apply(t,o),s=0;s<c.length;s++){var u=c[s];r="t"===u.type?r.then(u.next):r.catch(u.next)}p&&t.render.apply(t,p),a&&t.destroy.apply(t,a);for(s=0;s<i.length;s++)t.on.apply(t,i[s])};var u=new XMLHttpRequest;u.addEventListener("load",s),u.open("GET",r+"/loader.json",!0),u.responseType="json",u.send()
}(window,document,"Bots", "<sdk-folder-url>");
</script>
Then initialize the SDK by placing this snippet towards the end of the
body
section of your page. Replace <app-id>
with your app ID at the beginning of the script:
<script>
Bots.init({appId: '<app-id>'});
</script>
Browser support
The Bots Client JavaScript SDK supports all popular browsers.
Desktop Versions
- Chrome: The latest version along with the previous major version.
- Edge: The latest version along with the previous major version.
- Firefox: The latest version along with the previous major version.
- Internet Explorer: Version 11 and higher.
- Safari: The latest version along with the previous major version.
Mobile Versions
- Stock browser on Android 4.1 and higher.
- Safari on iOS 8 and higher.
Other Browsers
Although we only tested the SDK against these versions, it may be compatible with older browsers as well.
API
Individual Functions
init(options)
Initializes the Bots widget (the Web Messenger) in the web page using
the specified options. It returns a promise that will resolve when the
SDK is ready.
Note: Except for on
and off
,
all methods must be called after a successful init
. For
more about Bots.on
and Bots.off
, see Events.
Options
Option | Optional? | Default value | Description |
---|---|---|---|
appId |
No | The App ID generated by Digital Assistant when you create a channel. | |
locale |
Yes | en-US |
The locale that formats date using the |
soundNotificationEnabled |
Yes | true |
Enables the sound notification for new messages. |
browserStorage |
Yes | sessionStorage |
Limits the storage of the chat and the user identity to a single session. |
menuItems |
Yes | true |
Enables the client to display a menu different message types,
such as Upload Photo, Upload Document, or Share Location:
|
imageUploadEnabled |
Yes | true | Enables the image upload feature. |
embedded |
Yes | false | Tells the widget that it will be embedded. See Embedded Mode. |
customText |
Yes | See the following example. |
The strings used in the widget UI. You can use
these to either customize the text or translate it. Anything
enclosed in curly braces ( |
displayStyle |
Yes | How the messenger widget appears on your web site. This is defined as either a button or tab. You can style the button’s size and icon | |
buttonIconUrl |
Yes | The URL that points to the button icon. The icon image must be:
|
|
buttonWidth |
Yes | 8px |
The button width, in pixels. |
buttonHeight |
Yes | 58px |
The button height, in pixels. |
businessName |
Yes | The business name. For example: businessName: “Oracle” |
|
businessIconUrl |
Yes | The URL that points to the business’ icon image. This image must
be:
|
|
backgroundImageUrl |
Yes | The URL that points to the image that appears in the background of the conversation. This image is tiled to fit the chat window. | |
customColors |
Yes | The colors used in the UI. | |
brandColor |
Yes | 65758e |
The color used in the messenger header and for the button or tab in idle state. |
conversationColor |
Yes | 0099ff |
This color used for customer messages, quick replies and actions in the footer. |
actionColor |
Yes | 0099ff |
The color used to change the appearance of selected actions inside your messages, like tapped buttons or links. This color is also used for the Send button when it's in its active state. |
Example: Custom Colors
var initPromise = Bots.init({
appId: '<app-id>',
locale: 'en-US',
customColors: {
brandColor: '65758e',
conversationColor: '65758e',
actionColor: '65758e',
},
customText: {
actionPostbackError: 'An error occurred while processing your action. Please try again.',
clickToRetry: 'Message not delivered. Click to retry.',
conversationTimestampHeaderFormat: 'MMMM D YYYY, h:mm A',
fetchHistory: 'Load more',
fetchingHistory: 'Retrieving history...',
headerText: 'How can we help?',
inputPlaceholder: 'Type a message...',
invalidFileError: 'Only images are supported. Choose a file with a supported extension (jpg, jpeg, png, gif, or bmp).',
introductionText: 'We\'re here to talk, so ask us anything!',
locationNotSupported: 'Your browser does not support location services or it’s been disabled. Please type your location instead.',
locationSecurityRestriction: 'This website cannot access your location. Please type your location instead.',
locationSendingFailed: 'Could not send location',
locationServicesDenied: 'This website cannot access your location. Allow access in your settings or type your location instead.',
messageError: 'An error occurred while sending your message. Please try again.',
messageIndicatorTitlePlural: '({count}) New messages',
messageIndicatorTitleSingular: '({count}) New message',
messageRelativeTimeDay: '{value}d ago',
messageRelativeTimeHour: '{value}h ago',
messageRelativeTimeJustNow: 'just now',
messageRelativeTimeMinute: '{value}m ago',
messageTimestampFormat: 'hh:mm A',
messageSending: 'Sending...',
messageDelivered: 'Delivered',
sendButtonText: 'Send',
settingsHeaderText: 'Settings',
tapToRetry: 'Message not delivered. Tap to retry.',
unsupportedMessageType: 'Unsupported message type.',
unsupportedActionType: 'Unsupported action type.'
}
});
initPromise.then(function() {
// do something
});
// pass it around...
initPromise.then(function() {
//do something else
});
open()
Opens the conversation widget (no-op when embedded).
Bots.open();
close()
Closes the conversation widget (no-op when embedded).
Bots.close();
isOpened()
Tells if the widget is currently opened or closed.
Bots.isOpened();
destroy()
Destroys the widget, making it disappear. To get it
back, reinitialize the widget with init
. This also clears
the App ID from the widget and unbinds all of the listeners you might
have bound to it using Bots.on
. See Events.
Bots.destroy();
sendMessage(message)
Sends a message on the user’s behalf.
Bots.sendMessage({
type: 'text',
text: 'hello'
});
// OR
Bots.sendMessage('hello');
getConversation()
Returns the conversation (if it exists).
var conversation = Bots.getConversation();
startConversation()
Creates a user and a conversation on the server, allowing the business to reach out proactively to the user through the public API.
Important: Only call this method when a message is likely to be sent.
This method is called automatically when starting a conversation with
the sendMessage
method, or when a user sends a message
through the conversation view.
If a conversation already exists for the current user, this call is a no-op.
Bots.startConversation();
triggerPostback(actionId)
Triggers a postback action on the user's behalf. The actionId
is the _id
property of the targeted action. If you have
the _id
of the targeted postback action, you can pass it
directly to triggerPostback
:
const actionId = '5a747faa065bbe4e7804f2a4';
Bots.triggerPostback(actionId);
If you don't have the _id
for the action, you can get it
using Bots.getConversation()
. In the following sample,
this function passes the _id
for the Continue
conversation action from the log.
const conversation = Bots.getConversation();
console.log(conversation.messages);
// [
// {
// "text": "Do you want to continue?",
// "actions": [
// {
// "payload": "text:continue",
// "text": "Continue conversation",
// "_id": "5a7c65211aaa9b61f69c95e3",
// "type": "postback"
// }
// ],
// "type": "text",
// "role": "appMaker",
// "_id": "5a7c65211aaa9b61f69c95e2",
// // ...
// }
// ]
// Indicate to Bots SDK that the user has clicked on the "Continue conversation" postback action.
Bots.triggerPostback(conversation.messages[0].actions[0]._id);
updateUser(user)
Updates the user information.
Bots.updateUser({
givenName: 'Updated',
surname: 'Name',
email: 'updated@example.com',
properties: {
'justGotUpdated': true
}
});
Events
If you want to make sure your events are triggered, bind them before
calling Bots.init
.
To bind an event, use Bots.on(<event name>,
<handler>);
. To unbind events, you can either:
- Call
Bots.off(<event name>, handler)
to remove one specific handler. - Call
Bots.off(<event name>)
to remove all handlers for an event. - Call
Bots.off()
to unbind all handlers.
ready
This event triggers when init completes successfully. Be sure to bind
before calling init
.
Bots.on('ready', function(){
console.log('the init has completed!');
});
Bots.init(...);
destroy
This event triggers when the widget is destroyed.
Bots.on('destroy', function(){
console.log('the widget is destroyed!');
});
Bots.destroy();
message:received
This event triggers when the user receives a message.
Bots.on('message:received', function(message) {
console.log('the user received a message', message);
});
message:sent
This event triggers when the user sends a message.
Bots.on('message:sent', function(message) {
console.log('the user sent a message', message);
});
message
This event triggers when a message was added to the conversation.
Bots.on('message', function(message) {
console.log('a message was added to the conversation', message);
});
unreadCount
This event triggers when the number of unread messages changes.
Bots.on('unreadCount', function(unreadCount) {
console.log('the number of unread messages was updated', unreadCount);
});
widget:opened
This event triggers when the widget is opened.
Bots.on('widget:opened', function() {
console.log('Widget is opened!');
});
widget:closed
This event triggers when the widget is closed.
Bots.on('widget:closed', function() {
console.log('Widget is closed!');
});
Embedded Mode
As described above, to activate the embedded mode, you
need to pass embedded: true
when calling Bots.init
.
This disables the auto-rendering mechanism, so you will need to call Bots.render
manually. This method accepts a DOM element which will be used as the
container where the widget will be rendered.
The embedded widget will occupy the full width and height of the container. You must specify a height or else the widget will collapse.