Skip to main content
Skip table of contents

WebChat Integration Guide

Last updated:


About this guide

This document explains how to embed Omilia’s WebChat widget in your own website.

Requirements

Basic HTML & JS knowledge

Embed the chat widget on your website

To embed the chat widget to your website, go to the Chat tab of a miniApp, select a Locale and click the Get JS Code button. Copy the Javascript code with the Copy button and paste it to your website’s HTML code. Otherwise copy only the API key and URL Key from the JS code.

It is preferable to use the API URL in order to get new versions of chat delivered instantly. Using a downloaded chat file instead of URL causes a version lock, meaning you will no longer receive any updates.

Click the Try webchat! button to test the webchat.

Create the JS code manually

  1. Create the required script. Modify the code snippet by altering the values of the parameters in the table Parameters of chat widget integration script.

  2. To embed the WebChat widget in your website paste the code snippet within the body of the HTML code (preferably at the end). [1]

XML
<body>
  ...
  <script>

      (function(docElement, tag, rootElementId, bundleSrc, config, data) {
          var body = docElement.getElementsByTagName('body')[0];
          var div = docElement.createElement('div');
          div.id = rootElementId;
          body.appendChild(div);
          var element = docElement.createElement(tag);
          element.src = bundleSrc;
          element.type = 'text/javascript';
          var callback = function() {
            ChatBot.init({ rootElementId, config, data });
          };
          element.onload = callback;
          element.onreadystatechange = function() {
            this.readyState == 'complete' && callback();
          };
          body.appendChild(element);
      })

      (document, 'script', 'root-chatbot', 'https://assets.miniapps.ocp.ai/ChatWidget/bundle.js', {
          apiUrl: 'YOUR_API_URL',
          apiKey: 'YOUR_API_KEY'
      });
  </script>
</body>

Customers during WebChat initialization, can provide a configuration object (see section Configuration) and an initialization data object (see section Initialization Data).

Integration (Angular)

To embed the WebChat widget in an Angular Universal project, follow the steps below:

  1. Access DOM and add bundle script in head section using the following code:

JS
import {DOCUMENT} from "@angular/common";
import {Renderer2} from '@angular/core';

constructor(@Inject(DOCUMENT) private document: any, private renderer:Renderer2) {
}

constructor() {
  const scriptElt = this.renderer.createElement('script');
  this.renderer.setAttribute(scriptElt, 'type', 'text/javascript');
  this.renderer.setAttribute(scriptElt, 'src','https://assets.miniapps.ocp.ai/ChatWidget/bundle.js');
  this.renderer.appendChild(this.document.head, scriptElt);
}
  1. Add the rest of the script from the Angular component:

JS
ChatBot.init({
     rootElementId: 'your_chat_container,
     config: {
       apiUrl: 'your_API_URL',
       apiKey: 'your_APIkey',
       title:' Omilia Chat',
       logoUrl: 'data:image/svg+xml;base64,PD94bWwgdmVyc....',
       logoAlt: 'Alt attribute logo icon',
       logoBorder: false,
       bubbleUrl: './path/to/image.svg',
       bubbleAlt: 'Alt attribute bubble icon',
       brandColor: 'yourHTML_color',
    }
 });

Configuration

During the initialization of the WebChat, customers have the option to pass a set of configuration variables to customize the widget.


Parameter

Type

Required

Description

Value

apiUrl

string

Yes

Unique API URL of WebChat.

Can be extracted from the Javascript with Get JS Code as described in section Embed the chat widget on your website

apiUrls

Array<string>

No

WebChat provides an ability to have multiple API URLs so that it can have failover in case some URL is down. The parameter should be used along with the urlSelectMethod.

Any valid array of API URLs.

urlSelectMethod

string

No

The parameter only makes sense to use if apiUrls is specified. There are only two values that can be passed:

  1. ORDERED - chat picks the first API URL to connect from the apiUrls array. If the connection fails, the next API URL is picked (in order from first to last) and so on till the last API URL. If the last API URL fails, everything starts over.

  2. ROUND_ROBIN - every time chat is opened it picks a random API URL from the apiUrls array to connect to. If it fails to connect, the next random API URL will be picked except for the ones failed before. The chat will filter out failed API URLs and try to connect to the rest, if no API URLs are left everything starts over.

ORDERED, ROUND_ROBIN

apikey

string

Yes

Unique API key of WebChat.

Can be extracted from the Javascript with Get JS Code as described in section Embed the chat widget on your website

title

string

No

Sets the title of the widget.

Max character length 16 [2]

subtitle

string

No

Sets the subtitle of the widget.

Max character length 21

logoUrl

string

No

Sets the logo of the widget.

if an agent or a bot avatar parameter is specified, widget logo will be displayed only on the header, otherwise it will be displayed both the header and the agent/bot avatar.

Any valid path [3], or Base64 format

logoAlt

string

No

Sets the alt attribute for the logo icon.

Any valid

logoBorder

boolean

No

To hide or not the logo border.

Boolean value, by default is visible

dataPersistent

boolean

No

When true the data (either given during init or setData method) is persistent between sessions in an already loaded page. Data do not persist if the webpage is reloaded.

true/false. Default value false

bubbleUrl

string

No

To set the bubble icon of the chat widget.

Any valid path [3], or Base64 format

bubbleAlt

string

No

To set the alt attribute for the bubble icon.

Any valid string

enableResetButton

boolean

No

When the value is true, the webchat has a button that the user can click to reset the chat. When clicked, it calls the ChatBot.restart() method. When the value is false, the reset button is not visible.

true/false. Default value false

brandColor

string

No

To set the colour theme of the chat widget.

Any valid HTML colour

backgroundColor

string

No

Sets the color of the chat background.

Any valid HTNL color

enableConsecutiveDialogs

boolean

No

If it is true after the dialogue ends, the input box remains active (user can type), and inactive if it is false (user cannot type and needs to be restarted by closing and opening or by pressing the reset button).

true/false. Default value true

welcomeForm

FormProps

No

Provide an object with form properties to show the form at the beginning of the chat dialog. For more details see the Form section.

Form values

feedback

object

No

Feedback Configuration options:

type - Select an option based on when you want to initiate a feedback session::

  • 'always' - The feedback gathering process is activated after the termination of all dialogues.

  • 'agent' - The feedback gathering process is activated after the termination of dialogues that an agent had been involved.

  • 'bot' - The feedback gathering process is activated after the termination of dialogues that only an OCP application had been involved.

form (required) - This configuration displays a feedback form after a dialogue has ended.

If feedback is configured, then at the end of a conversation (as specified in type), the webchat widget will optionally present a form as defined. If the form is not configured, this step will be skipped. Either way, once the form is filled in or bypassed, the webchat widget will trigger a re-invocation of the same application with the intent provide_feedback, and the following data attached:

  • the id of the previous dialogue

  • the form data, if applicable

Example:

JS
feedback: {
  type: 'always',
  form: {
    title: 'Feedback Form',
    required: false,
    fields: [
      {
        type: 'input',
        email: true,
        order: 1,
        required: false,
        label: 'Opinion',
        placeholder: 'Type here...',
        name: 'opinion',
      },
    ],
  }
}

For more information on how to configure a form please visit the Form section.

ga

boolean

No

Enables Google Analytics tracking.

true/false. Default value false

enableTranscriptDownload

boolean

No

Enables “Download as PDF“ button in the end of the dialog, by clicking on which chat transcription will be downloaded.

true/false. Default value false

font

string

No

Pass any font name from GoogleFonts to change WebChat’s font.

A string with a font name.
Examples: “Roboto“, “Open Sans“, “Open Sans:500“, “Lato:200italic“, “Lato:italic“.

notifications

object

No

Enables chat notifications.

withBubble shows red (default color) dot next to the chat bubble.

withNumber show number of messages inside of notification bubble.

withTitle enables notification messages in the website tab title. It toggles the title each second from e.g. "Jira - Board" to "(X) New Messages!", where X is the number of messages received.

withSound enables sound notifications.

audioSrc - URL for custom notifications sound (if not specified the default sound will be used).

Default values:

JS
notifications: {
  withBubble: false,
  withNumber: true,
  withTitle: false,
  withSound: false,
  audioSrc: '';
}

footer

Object

No

Shows footer text at the bottom of the chat.

showFooter - shows footer. The default Powered by Omilia text will be shown if text and logoURL parameters are empty.

text is the footer text.

logoURL is the URL of the footer image.

JS
footer: {
  showFooter: false,
  text: '',
  logoURL: '',
}

agent

Object

No

Configure agent’s name and avatar

name - set agent’s name.

withName - show/hide name. Default is false

avatar - URL for agent’s photo.

JS
agent: {
  name: '',
  withName: false,
  avatar: '',
}

bot

Object

No

Configure bot’s name and avatar

name - set bot’s name.

withName - show/hide name. Default is false.

avatar - URL for bot’s photo

JS
bot: {
  name: '',
  withName: false,
  avatar: '',
}

shouldReopenMinimizedChat

string

No

ALWAYS - after chat is minimized it will be reopened when users go to different website sections in the same tab, reload the page, or open new tabs.

NEVER - after chat is minimized it will not be reopened when users go to different website sections in the same tab, reload the page, or open new tabs.

NEXT_TABS - after chat is minimized it will not be reopened unless users go to different sections of the website in the same tab or reload the page's current page. In the newly opened tabs chat will be opened.

JS
shouldReopenMinimizedChat: 'NEXT_TABS'

Default value: NEXT_TABS

crossTabSync

boolean

No

crossTabSync: true - all chats in different browser tabs of the same website will have a common dialog (all messages from chat and user will be synchronized).
crossTabSync: false - each chat in different browser tabs of the same website will have their own dialog. Bot/Agent and User messages will not be synchronized.

CODE
crossTabSync: false

Default value: true

Table 1. Parameters of chat widget integration script

JS
config = {
    apiUrl: '<YOUR_API_URL>',
    apiKey: '<YOUR_API_KEY>',
    title:' Omilia Chat',
    logoUrl: 'data:image/svg+xml;base64,PD94bWwgdmVyc....',
    logoAlt: 'Alt attribute logo icon',
    logoBorder: false,
    bubbleUrl: './path/to/image.svg',
    bubbleAlt: 'Alt attribute bubble icon',
    brandColor: '<YOUR_HTML_COLOR>'
}

Example configuration object

Initialization Data

During the initialization of the WebChat, customers have the option to pass their own data (for example, key-value pairs). Initialization data are transmitted when a new dialog starts and used by OCP to improve the conversational experiences of users.

Make sure data contains only whatever is necessary to improve the experience of the users.

JS
data = {
    userName: 'bilbo',
    firstName: 'Bilbo',
    lastName: 'Baggins'
    customerNumber: '345453543544'
    bearerToken: 'feawfjklej9820jr39802edj032#$23rni32ojrnkd23oj8230'
}

Example initialization object

Data object does not support complex data structures, for example, arrays or nested object.

An alternative way for customers is to use the setData method on the widget.

JS
ChatBot.setData({
    userName: 'bilbo',
    firstName: 'Bilbo',
    lastName: 'Baggins'
    customerNumber: '345453543544'
    bearerToken: 'feawfjklej9820jr39802edj032#$23rni32ojrnkd23oj8230'
})

It can be used only when ChatBot is fully initialized. If you want to call setData right after Chat.init, it would be safer to move this data directly in the init method.

Data that have been set during intialization or with setData method, are sent only when one clicks the WebChat bubble to open or clicks the reset button.

Every time setData is used, it overwrites previous data.

Event Callback

WebChat can provide chat events by setting up an appropriate callback method.

JS
ChatBot.setEventCallback(event -> () {


})

The Event object has the following structure:

JS
event = {
    type: 'route',
    meta: {
      key1: 'value1',
      key2: 'value2'
    }
}

Property

Type

Description

Value

Type

string

Type of the event

start_dialog, route, end_dialog

meta

object

Depending on the event type meta might contain different key-value pairs.

(TO BE DETERMINED)

Table 2. Parameters

At the moment, this method is triggered only when we have key meta data inside the event. It might not be triggered on the events that do not give or reset meta information.

Event Subscribe

WebChat provides a method to subscribe to the events.

JS
ChatBot.subscribe('onOpen', isOpen => {
  if (isOpen) {
    ChatBot.setData(data); 
  }
});

ChatBot.subscribe('onMinimized', isMinimized => {
  console.log('isMinimized', isMinimized); 
})

Event

Description

onOpen

Triggered when the chat opens or closed.

You can use this event if you want to set data with ChatBot.setData() and make sure that it will be sent on the initial request at the start of the upcoming chat session.

onMinimized

Triggered when the chat is minimized or maximized.

Open Chat

WebChat provides a method to open the chat proactively. You can call it without arguments or providing a text utterance.

JS
ChatBot.open();
ChatBot.open('How to reset a password?')

State

After method call

Description

Open method called without any arguments

Opened

The WebChat is opened and initialized as if manually clicked on a chat bubble.

Open method called with utterance

Opened

The WebChat is opened and initialized with the utterance. The utterance sent by the website is not visible when the chat is opened.

If the ChatBot.setData() is called before then the chat will be initialized with data from setData method.

Close Chat

WebChat provides a method to close the current chat. A "close" resets the Chat and closes the connection.

CODE
ChatBot.close()

State

After method call

Description

WebChat windows is open and a chat is in progress or terminated

Closed

The chat closes and disconnects any open connections. Any dialog in progress will be lost.

WebChat is closed and only the chat bubble is visible

Closed

The chat remains closed.

Table 4. UX Close description

The close method does NOT clear the data that was set with the setData method, if the dataPersistent is true. If you need to change the aforementioned data, you need to call setData again.

Restart Chat

State

After method call

Description

WebChat windows is open, and a chat is in progress or terminated

Open

The chat closes and reopens in an instant. It disconnects any open connections. Any dialog in progress will be lost. It initializes a new chat, and the dialogs from previous chat are neither visible nor retrievable.

WebChat is closed and only the chat bubble is visible

Open

The chat opens in an instant. It initializes a new chat, and the dialogs from previous chat sessions are neither visible nor retrievable

Table 3. UX Restart description

The restart method does NOT clear the data that was set with the setData method, if the dataPersistent is true. If you need to change the aforementioned data, you need to call setData again.

Form

There are two instances when you can display a form:

  1. Before the dialogue: Place the form configuration in the welcomeForm field found at the root of the configuration object.

  2. At the end of the dialogue: This is used as part of the feedback-gathering process. For this instance, place the form configuration in the appropriate form field within the feedback object.

The maximum number of form elements is limited to five.

JS
{
  title: 'Form to fill in',
  subtitle: 'Fill in all fields in the form',
  required: false,
  fields: [
    {
      type: 'input',
      email: true,
      order: 1,
      required: false,
      label: 'Email',
      placeholder: 'Email',
      name: 'email',
    },
    {
      type: 'checkbox',
      order: 5,
      name: 'terms_conditions',
      required: true,
      label: 'Terms & Conditions',
    },
    {
      type: 'select',
      order: 3,
      name: 'countries',
      required: false,
      label: 'Countries',
      placeholder: 'Pick an option',
      value: { label: 'Ukraine', value: 'ukraine' },
      options: [
        { label: 'Ukraine', value: 'ukraine' },
        { label: 'Greece', value: 'greece' },
        { label: 'USA', value: 'usa' },
        { label: 'France', value: 'france' },
        { label: 'Poland', value: 'poland' },
      ],
    },
  ],
},

Form Props

Field

Required

Type

Description

title

No

string

A title of the form

subtitle

No

string

A subtitle of the form

required

Yes

boolean

true - form can’t be skipped and should be submitted.

false - form is optional, can be skipped

fields

Yes

FormFields

Array of FormField objects

Form Field: Input

Field

Required

Type

Description

type

Yes

'input'

Defines a type of the displayed form element

name

Yes

string

Used as key for the form values object

value

No

string

Input’s value

required

No

boolean

Defines if the input is required field to submit the form

label

Yes

string

Input’s label

error

No

string

Error message. Appears in case of the field validation error.

  • Default error if the input is required: This field is required

  • Default error for alphanumeric input: Please enter only letters and number

  • Default error for email only input: Please enter an email address

order

Yes

number

Defines an order in which input will be displayed among other form elements from top to bottom

email

No

boolean

If true, the input will accept only emails as value

placeholder

No

string

Input’s placeholder

Form Field: Select

Field

Required

Type

Description

type

Yes

'select'

Defines a type of the displayed form element

name

Yes

string

Used as key for the form values object

value

No

{ label: string, value: string }

A label is displayed in the select options.

A value is used as key for the form values object

options

Yes

Array{ label: string, value: string }

Select options. Max number of options is limited to 5, e.g. if you provide 7 options only first 5 will be displayed.

required

No

boolean

Defines if the select is required field to submit the form

label

Yes

string

Select’s label

error

No

string

Error message. Appears in case of the field validation error.

  • Default error if the input is required: This field is required

order

Yes

number

Defines an order in which select will be displayed among other form elements from top to bottom

placeholder

No

string

Select’s placeholder

Form Field: Checkbox

Field

Required

Type

Description

type

Yes

'checkbox'

Defines a type of the displayed form element

name

Yes

string

Used as key for the form values object

value

No

boolean

Default value of the checkbox

link

No

string

  1. The value should be a link

  2. Should start with https or http

  3. Can be with www or without.

Examples:

  • https://www.google.com

  • http://www.google.com

  • http://google.com

required

No

boolean

Defines if the checkbox is required field to submit the form

label

Yes

string

Checkbox’s label

error

No

string

Error message. Appears in case of the field validation error.

  • Default error if the input is required: This field is required

order

Yes

number

Defines an order in which checkbox will be displayed among other form elements from top to bottom

Google Analytics Integration

WebChat supports Google Tag Manager and Global Site Tag (gtag.js) integrations. You can use only one of these approaches, not both at the same time.

To enable chat analytics please pass ga: true parameter to the configuration object of the WebChat

Steps to add Google Analytics to your website:

Global Site Tag (gtag.js)

Go to your Google Analytics to find this script.

Copy and paste it in the code of every page of your website, immediately after the <head> element. Don’t add more than one Google tag to each page.

NOTE: Google ID in the script below is not real. You should copy the script with your personal Google ID from your Google Analytics account.

XML
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-D2KL1GKXCD"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-D2KL1GKXCD');
</script>

Google Tag Manager

Go to the Tag Manager account

Copy the code below and paste it on to every page of your website.

NOTE: Google ID in the scripts below is not real. You should copy the scripts with your personal Google ID from your Google Analytics account.

Paste this code as high in the <head> of the page as possible:

XML
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-ASGFQW2');</script>
<!-- End Google Tag Manager -->

Additionally, paste this code immediately after the opening <body> tag:

XML
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-ASGFQW2"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Events

Custom analytics events that are sent by WebChat:

Event name

Event data

Description

chatOpened

Current URL

Fires when the Chat Widget Window is opening

chatClosed

Current URL

Fires when the Chat Widget Window is closing

agentTransfer

Current URL

Fires when the process of transferring to the live agent is started

agentConnected

transfer_id, agent_label, agent_id, dialog_id, current URL

Fires when agent is connected.

It is guaranteed that only the current URL will be sent to GA. The remaining fields may not be presented in the event data.


[1] Code snippet can be minified

[2] Including spaces

[3] To an SVG or png file with 60px X 60px size


Comment about this article and provide feedback

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.