Teneo Web Chat - Javascript API

About the API

The Teneo Web Chat JavaScript API allows you to interact with the Teneo Web Chat widget embedded on your site. This lets you change or extend its behavior in ways that are not provided by the standard configuration.

This page focuses on developers and requires a basic knowledge of JavaScript. If you have any questions, don't hesitate to add a new topic on the Teneo Developers Forum.

Getting started

The API is accessed through the TeneoWebChat object. It is being initialized as part of the code that is used to install the Teneo Web Chat widget on your site. If you haven't yet added the code to your (development) site, follow the instructions here.

The API is available for Teneo Web Chat v3.0.0 or higher. If you are using an older version of Teneo Web Chat and the API presented here doesn't work, you should update to the latest version. As of version 3.0.0 you can check the current version by calling the version function:

TeneoWebChat.version()

The TeneoWebChat object comes with the following functions:

  • call - allows you to invoke methods
  • get - makes it possible to fetch data
  • on - registers a callback function for a specific event
  • off - removes a callback registered by on

The usage of these functions is based on passing the correct arguments in the following pattern:

TeneoWebChat.function('method', 'data')

For example, if you would like to send an input 'Hello world!' to Teneo, this is what it would look like:

TeneoWebChat.call('send_input',  {'text':'Hello world!'})

Handled state object

The payload of the on callbacks may contain an object called handledState. When this object is available, you can prevent Teneo Web Chat from executing the default behavour of the callback.

Object details
Key Type Description
handled boolean Default value: false. If set to true, tells Teneo Web Chat that your custom function handles the callback's behavior and Teneo Web Chat should not exectute the default behaviour after the callback has been executed.

For example:

function askForConfirmationBeforeClose(payload) {
    // get the handledState object
    const handledState = payload.handledState

    // prevent chat window from being closed
    handledState.handled = true

    // functionality to ask for confirmation before we close the window
    // for example by displaying a modal message
    TeneoWebChat.call('add_message', myModalMessage)
}

TeneoWebChat.on('close_button_clicked', askForConfirmationBeforeClose)

Methods

To trigger Teneo Web Chat events, you can use the following methods:

  • Maximize
  • Minimize
  • Send input
  • End session
  • Clear chat history
  • Reset
  • Add message
  • Show typing indicator
  • Hide typing indicator
  • Set chat window title
  • Set chat window icon
  • Reset chat window icon
  • Set launch icon
  • Reset launch icon
  • Disable user input
  • Enable user input

Maximize

Maximizes the Teneo Web Chat window.

TeneoWebChat.call('maximize')

Minimize

Minimizes the Teneo Web Chat window.

TeneoWebChat.call('minimize')

Send input

Sends a request to Teneo. A new message with the input text will be appended to the message history.

TeneoWebChat.call('send_input', message)
Message payload
Param Type Description
text string Mandatory. The input to send to engine. To send an empty input, use an empty string as value.
parameters object Optional. Additional input parameters to include in the request
silent boolean Optional. If true, the input will be sent without adding a new message bubble to the message history. Defaults to false.
Message payload example
{
    "text": "Hello!",
    "parameters": {
        "countryCode": "NL"
    },
    "silent": false
}

End session

Sends an end session request to Teneo.

TeneoWebChat.call('end_session')

Clear chat history

Clears the message history that is shown in the Teneo Web Chat window.

TeneoWebChat.call('clear_chat_history')

Reset

Resets Teneo Web Chat. This means the chat history will be deleted, an end session request is sent to engine and the chat window is minimized.

TeneoWebChat.call('reset')

Add message

Adds a message to the message history shown in the chat window. Note: this only adds a message to the list, it does not send an input to Teneo. To send a request to Teneo, use Send input.

TeneoWebChat.call('add_message', message)
Message payload
Param Type Description
type string Required. The type of message. Valid values:
text
audio
buttons
card
clickablelist
combo
filevideo
image
quickreply
system
vimeovideo
youtubevideo
author text Optional. Message author type. Only needed for messages of type 'text'. Valid values:
agent
bot
user
data object Required. The message data. For messages of type 'text', the valid keys are:
text - The message text.
dateline - Optional dateline shown above the text bubble.
avatarUrl - Optional URL to an avater image that should be shown next to the text bubble.
For other message types, see the Message types specifications of Teneo Web Chat.
Message payload example
{
    "author": "bot",
    "type": "text",
    "data": {
        "avatarUrl": "https://url.to/image/bot.png",
        "dateline": "Sara - 12:46",
        "text": "Hello world!"
    }
}

Show typing indicator

Shows a typing indicator bubble for a particular author in the message history. If the typing indicator is shown and a new messsage with the same author type is added, the typing indicator will be removed. To explicitly remove the typing indicator, see Hide typing indicator.

TeneoWebChat.call('show_typing_indicator', indicator)
Indicator payload
Param Type Description
author text Indicator author type. Required. Valid values:
agent
bot
user
data object Additional information to be shown alongside the typing indicator. Valid keys are:
dateline - Optional dateline shown above the typing bubble.
avatarUrl - Optional URL to an avater image that should be shown next to the typing indicator.
Indicator payload example
{
    "author": "agent",
    "data": {
        "avatarUrl": "https://url.to/image/agent.png",
        "dateline": "Agent",
    }
}

Hide typing indicator

Hides the typing indicator for a particular author.

TeneoWebChat.call('hide_typing_indicator', indicator)
Indicator payload
Param Type Description
author text Indicator author type. Required. Valid values:
agent
bot
user
Indicator payload example
{
    "author": "agent"
}

Set chat window title

Updates the title shown in the header of the Teneo Web Chat window.

TeneoWebChat.call('set_chat_window_title','New title')

Set chat window icon

Updates the icon shown in the header of the Teneo Web Chat window.

TeneoWebChat.call('set_chat_window_icon','https://url.to//icon.svg')

Reset chat window icon

Resets the icon shown in the header of the Teneo Web Chat window to the default icon.

TeneoWebChat.call('reset_chat_window_icon')

Note: this will reset the icon to the default icon that comes with Teneo Web Chat. If you have specified a custom icon using the 'titleIconUrl' configuration setting, you should instead use the Set chat window icon api and provide the url used for 'titleIconUrl'.

Set launch icon

Updates the icon shown in the Teneo Web Chat launch button.

TeneoWebChat.call('set_launch_icon','https://url.to//icon.svg')

Reset launch icon

Resets the icon shown in the Teneo Web Chat launch button to the default icon.

TeneoWebChat.call('reset_launch_icon')

Note: this will reset the icon to the default icon that comes with Teneo Web Chat. If you have specified a custom icon using the 'launchIconUrl' configuration setting, you should instead use the Set launch icon api and provide the url used for 'launchIconUrl'.

Disable user input

Disables the user input field.

TeneoWebChat.call('disable_user_input')

Enable user input

Enables the user input field.

TeneoWebChat.call('enable_user_input')

Getters

You can use getters to fetch data from Teneo Web Chat. These are the getters currently supported:

  • Get state
  • Get message list
  • Get engine URL

Get state

Returns an object with the Teneo Web Chat window state.

TeneoWebChat.get('state')
Response object
Param Type Description
visibility string The Teneo Web Chat window's visibility. Possible values:
maximized
minimized

Get chat history

Returns the chat history as a list of message objects. For message object details, see: Add message.

TeneoWebChat.get('chat_history')

Get engine URL

Returns an object containing the URL of the Teneo Engine.

TeneoWebChat.get('engine_url')
Response object
Param Type Description
engineUrl string The URL of the Teneo Engine.

Callbacks

Callbacks allow you to react to the events triggered by Teneo Web Chat. You can use them to modify the behavior of Teneo Web Chat when certain events happen. These are the callbacks currently supported:

  • On ready
  • On open button clicked
  • On minimize button clicked
  • On close button clicked
  • On visibility changed
  • On user typing
  • On input submitted
  • On message button clicked
  • On modal button clicked
  • On engine request
  • On engine response
  • On new message

For example, this is the order of the callbacks when a user sends an input and receives a text answer from the bot:

User action Callback
Sends input On input submitted
On new message
On engine request
Receives an answer On engine response
On new message

On ready

Teneo Web Chat has finished loading.

Example
function onReady() {
  // Teneo Web Chat is ready
  console.log("Teneo Web Chat is ready")
}

TeneoWebChat.on('ready', onReady)

On open button clicked

Called when the button to open the chat window is clicked, but before the chat window is actually opened. Note: this event is not called when the window is maximized using the api.

Payload
Param Type Description
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the chat window should not be maximized.
function onOpenButtonClicked(payload) {
    // handle open button clicked event
    console.log("Open button clicked")
}

TeneoWebChat.on('open_button_clicked', onOpenButtonClicked)

On minimize button clicked

Called when the button to minimize the chat window is clicked, but before the chat window is actually minimized. Note: this event is not called when the window is minimized using the api.

Payload
Param Type Description
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the chat window should not be minimized.
function onMinimizeButtonClicked(payload) {
    // handle minimize button clicked event
    console.log("Minimize button clicked")
}

TeneoWebChat.on('minimize_button_clicked', onMinimizeButtonClicked)

On close button clicked

Called when the button to close the chat window is clicked but before the chat window is actually reset. Note: this event is not called when the window is minimized or reset using the api.

Payload
Param Type Description
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the chat window should not be reset.
function onCloseButtonClicked(payload) {
    // handle close button clicked event
    console.log("Close button clicked")
}

TeneoWebChat.on('close_button_clicked', onCloseButtonClicked)

By default, the close chat button is not visible in the header. To enable it, the property showCloseButton with value true should be passed on when initializing Teneo Web Chat.

On visibility changed

Called once the visibility of the Teneo Web Chat window has changed. This applies to both user actions like maximizing or minimizing the window as well as maximizing or minimizing the Teneo Web Chat window through the use of this API.

Payload
Param Type Description
visibility string The Teneo Web Chat window's visibility. Possible values:
maximized,
minimized
Example
function onVisibilityChanged(payload) {
  switch (payload.visibility) {
    case 'maximized':
      break
    case 'minimized':
      break
  }
}

TeneoWebChat.on('visibility_changed', onVisibilityChanged)

On user typing

Called when the user is typing a message in the input box. Called approx once per 250ms.

Payload
Param Type Description
text string The text of the message typed so far.
Example
function onUserTyping(payload) {
    // handle user typing event
    const text = payload.text
    console.log(text)
}

TeneoWebChat.on('user_typing', onUserTyping)

On input submitted

Called when the user submits an input by submitting it from the input box. This is called before the message is added to the message list and before the message is sent to engine.

Payload
Param Type Description
text string The text of the message.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the input will not be submitted.
Example
function onInputSubmitted(payload) {
    // handle input submitted event
    let text = payload.text
    console.log(text)
}

TeneoWebChat.on('input_submitted', onInputSubmitted)

On message button clicked

Called when the user submits an input by clicking a button, quickreply or a clickable list. This is called before the postback value is (silently) sent to engine.

Payload
Param Type Description
button object Details of the clicked button. See button, quickreply or clickable list for details of the clickable items.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the postback value will not be sent to engine.
Example
function onMessageButtonClicked(payload) {
    // handle message button clicked event
    var button = payload.button
    console.log("Button clicked, postback value:", button.postback)
}

TeneoWebChat.on('message_button_clicked', onMessageButtonClicked)

On modal button clicked

Called when the user clicks button in a modal message. This is called before the postback value is (silently) sent to engine.

Payload
Param Type Description
button object Details of the clicked button. See Modal message for button details.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the postback value of the button will not be sent to engine.
Example
function onModalButtonClicked(payload) {
    // handle modal button clicked event
    var button = payload.button
    console.log("Button clicked, postback value:", button.postback)
}

TeneoWebChat.on('modal_button_clicked', onModalButtonClicked)

On engine request

Called before a request is sent to engine.

Payload
Param Type Description
requestDetails object Object containing the details to be sent to engine. Contains the following keys:
channel - Channel parameter. Default value: 'teneo-webchat'
text - The user input.
[extra parameters] - Additional parameters included in the request.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the request will not be sent to engine.
Example
function onEngineRequest(payload) {
    // handle onEngineRequest event
    var requestDetails = payload.requestDetails
    if (requestDetails.text) {
        console.log(requestDetails.text)
    }
}

TeneoWebChat.on('engine_request', onEngineRequest)

On engine response

Called when a response from engine was received, but before the results (messages, components) are added to the message list.

Payload
Param Type Description
responseDetails object The repsone object as returned by Teneo Engine. See Engine Response for details.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and the response will not be further processed (and no message will be added to the message list).
Example
function onEngineResponse(payload) {
    // handle engine response event
    var response = payload.responseDetails
    console.log("Answer text", response.output.text)
}

TeneoWebChat.on('engine_response', onEngineResponse)

On new message

Called when a both an incoming and outgoing message is added to the message list.

Payload
Param Type Description
message object Contains the details of the message that be added to the message list. See Add message for details.
handledState object Contains key 'handled' with boolean value false. If set to true, tells Teneo Web Chat that your callback function overrides the default behaviour and message will not be added to the message list.
Example
function onNewMessage(payload) {
  const message = payload.message
  switch (message.type) {
    case 'text':
      // handle new text message event
      console.log(message.data.text)
      break

    case 'card':
      // handle new card message event
      console.log(message.data.title)
      break

    default:
      break
  }
}

TeneoWebChat.on('new_message', onNewMessage)

Examples

Open the chat window using a button

var chatButtonOpen = document.getElementById('chat-btn-open')
chatButtonOpen.addEventListener('click', function() {
  TeneoWebChat.call('maximize')
})

Open the chat window after 30 seconds

setTimeout(function() {
    TeneoWebChat.call('maximize')
}, 30000)

Modify a message before it is added to the message list

Let's say you want to replace all occurrences of the word 'love' in any text message with the ❤️ emoji.

function handleNewMessage(payload) {
  message = payload.message
  if (message.type == "text" && message.data.text) {
    message.data.text = message.data.text.replace(/love/g,'❤️')
  }
}
TeneoWebChat.on('new_message', handleNewMessage)

Manage window state between pages

By default the Teneo Web Chat window is minimized when a page is loaded. Suppose you would like the web chat window to stay open when the user moves from page to page.

function rememberVisibilityState(payload) {
  sessionStorage.setItem('twc_last_state', payload.visibility);
}

function restoreWindowState() {
  var lastState = sessionStorage.getItem('twc_last_state');
  if (lastState === 'maximized') {
    TeneoWebChat.call('maximize');
  } else {
    TeneoWebChat.call('minimized');
  }    
}

TeneoWebChat.on('visibility_changed', rememberVisibilityState);
TeneoWebChat.on('ready', restoreWindowState);

Add a system message

Sometimes you may wish to add a message to the message history that is not from the bot or the user.

var systemMessage = {
    'type': 'system',
    'data': {
        'text': 'You will be handed over to an agent. You are number <strong>4</strong> in the queue.'
    }
}

TeneoWebChat.call('add_message', systemMessage)

Delay bot response and show typing indicator

You can use the api to delay the bot's response and show a typing indicator during the delay time:

// pick a random number between two values
function randomIntFromInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function botTypingIndicator(payload) {
    const message = payload.message

    // only proceed if the message that is added to the message list is from the bot
    if (message.author === "bot") {

        // immediately show a typing indicator, but only for text messages
        if (message.type === "text") {
            // show a typing indicator for author bot
            TeneoWebChat.call('show_typing_indicator', {"author":"bot"}) 
        }

        // add a delay between 600 and 1000 milliseconds before messages are shown
        return new Promise(function(resolve) {
            setTimeout(function() {
                resolve(payload);
            }, randomIntFromInterval(600,1000));
        });
    }
}

TeneoWebChat.on('new_message', botTypingIndicator);

Was this page helpful?