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.

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]

<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>
XML

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:

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);
}
XML
  1. Add the rest of the script from the Angular component:

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',
    }
 });
CODE

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]

logoUrl

string

No

Sets the logo of the widget

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

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

form

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

ga

boolean

No

Enables Google Analytics tracking

true/false. Default value false

Table 1. Parameters of chat widget integration script

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>'
}
CODE

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.

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

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.

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

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.

ChatBot.setEventCallback(event -> () {


})
CODE

The Event object has the following structure:

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

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.

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

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

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.

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

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.

ChatBot.close()
CODE

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

WebChat allows showing a form when the widget opens before the dialog is started.

The maximum number of form elements is limited to 5.

form: {
  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' },
      ],
    },
  ],
},
JS

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.

<!-- 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>
CODE

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:

<!-- 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 -->
CODE

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

<!-- 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) -->
CODE

Events

Custom analytics events that are sent by WebChat:

Event name

Event data

Description

chatOpened

Current URL

Fires when the chat is opening

chatClosed

Current URL

Fires when the chat is closing

agentTransfer

Current URL

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


[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