🆕Web V2 methods and options

The article below will deep dive in technical possibilities of our new Web widget (V2).

From 31st October 2024, all Chatlayer customers using the Web channel will need to switch to the new web widget, Web V2. This means that Web V1 will be removed from our codebase. Learn everything about moving from V1 to V2.

All methods

Method DescriptionArgumentsRead more on

Chatlayer.init()

Initializes the widget using the specified options. This method returns a promise like object.

(options: Options)

Chatlayer.open()

Opens the widget.

Chatlayer.close()

Closes the widget.

Chatlayer.toggle()

If widget is closed, it opens it and vice-versa.

Chatlayer.destroy()

Destroys the widget

Chatlayer.isOpen()

Shows whether the widget is open.

Chatlayer.login()

To federate the customer identity with the ones of your website or application.

(externalId: string, jwt: string)

Chatlayer.logout()

Closes the session and a new conversation will start from scratch.

(externalId: string, jwt: string)

Chatlayer.on()

Subscribe to predefined and custom events throughout the user conversation with your bot.

(event, (arg1, arg2) => ...)

Chatlayer.off()

Stop tracking or unsubscribe from receiving the events set in Chatlayer.on.

Chatlayer.setLanguage()

Set the current language. Only languages on the list of languages supported by your bot will be accepted.

Chatlayer.language()

The current language of the widget.

Chatlayer.setSessionData()

Sets extra data in the conversation session and returns a promise.

Chatlayer.getCustomer()

Retrieves session data from Internal.user and custom fields added to it.

Chatlayer.sendMessage()

Sends a message on the user’s behalf, if they click a button on the page, for example.

(text)

Chatlayer.track()

Creates a new event that will be tracked.

e.g: Chatlayer.track

("view_product”, product_id: "SKU123"})

Chatlayer.trackEvent()

Track events occuring on your site or app.

(eventName: string, eventAttributes: Record<string,any>)

Chatlayer.render()

This method can be used if you want the widget embedded on a page.

Chatlayer.startTyping()

Shows the typing indicator

(sender)

Chatlayer.stopTyping()

Hides the active typing indicator

Chatlayer.createConversation()

Starts a new empty conversation while maintaining the customer information

Chatlayer.setDelegate()

Allows you to set a custom delegate for the agent avatar and name displayed

DelegateConfig


Initialize the Web widget with options

'Chatlayer.init(options: Options)'

This Initialize the Web widget using the specified options. This method returns a promise-like object.

Note that except for the on and off methods, the rest of the documented methods below needs to be called after init is completed.

Options

The Options can be:

OptionIs optionalDafault valueType

channelId

No

-

string

The ID of the Chatlayer channel

title

Yes

-

string

The title to show in the header widget

subtitle

No

-

string

An optional subtitle to show below the title

position

No

right

right | left

The position of the widget. Possible values are left or right

buttonWidth

No

58

number

The width of the widget button

buttonHeight

No

58

number

The height of the widget button

Yes

-

CustomColors

Override the colors of the widget

headerIconUrl

Yes

-

url

URL of a public image to be shown in the header

region

Yes

eu-west1-gcp

string

The region of your Chatlayer account

Yes

-

CustomText

Override the text of the different widget UI elements

enableTextInput

No

true

boolean

Set it to false to hide the text input, allowing users to interact only via buttons and quick replies

enableAudioInput

No

true

boolean

Set it to false to hide the audio recording button, preventing the users from sending audio messages via the widget

enableFileUpload

No

true

boolean

Set it to false to hidde the file upload button, preventing the users sending files via the widget. File upload request will still work

enableSoundNotifications

No

true

boolean

Control whether the user will receive sound notifications every time a new message arrives. It can be changed by the user as well from the settings

No

-

PrechatForm

Information collection using a form before the chat starts

delegate

No

-

DelegateConfig

Set a delegate for the conversation. Check Setting a delegatefor more details

customColors

The customColors can be:

Option

Optional

Default Value

Description

brandColor

Yes

007171

This color will be used in the messenger header and the launcher. It must be a 3 or 6-character hexadecimal color.

conversationColor

Yes

007171

This color will be used for customer messages, quick replies and actions in the footer.

actionColor

Yes

007171

This color will be used for call-to-actions inside your messages. Must be a 3 or 6-character hexadecimal color.

customText

customText can be:

Option

Optional

Default Value

Description

inputPlaceholder

Yes

Send a message

Placeholder text shown in the message input field

botDisplayName

Yes

Bot

This display name of the bot. Use an empty string to hide it.

agentDisplayName

Yes

Agent

This display name of the agent. Use an empty string to hide it.

To provide different values for different languages, add a subfield with the language code.

prechatForm

The prechatForm is one of the options that we have in the Web widget to configure a form with a set of input fields before beginning the chat.

Internally, it consists of an array of Element Definitions. Each element can have following type, label, placeholder and variant.

Name

Type

Description

Applies to

type

String

The type of element

One of text, spacer, input, select, checkbox, button, textarea, image

label

String

The text that goes on top of the input field

input, textarea, select, checkbox

placeholder

String

The sample text in the field

input, textarea, select, checkbox

variant

String

The element variant

One of primary, secondary | button

Code example on how to use prechatForm and its elements
// Code sample that shows how to use prechatForm and its elements.  
<script type="application/javascript">Chatlayer.init(Chatlayer.init({"channelId": "YOUR_CHANNEL_ID", "region": "eu-west1-gcp", "position": "right", 
            "prechatForm": {
            elements: [
              {
                id: 'age',
                type: 'input',
                label: 'Age',
                required: true,
                variant: 'number',
                placeholder: 'Placeholder text...',
              },
              {
                id: 'email',
                type: 'input',
                variant: 'email',
                label: 'Email',
                defaultValue: 'a@a.com',
                placeholder: 'Placeholder text...',
              },
              {
                id: 'website',
                type: 'input',
                label: 'Company website',
                placeholder: 'Placeholder text...',
              },
              {
                type: 'select',
                id: 'checkbox-1',
                label: 'Select Label',
                placeholder: 'Select company size',
                options: [
                  {
                    id: 'option-1',
                    type: 'option',
                    label: 'Option 1',
                  },
                  {
                    id: 'option-2',
                    type: 'option',
                    label: 'Option 2',
                  },
                  {
                    id: 'option-3',
                    type: 'option',
                    label: 'Option 3 (Disabled)',
                    disabled: true,
                  },
                ],
              },
              {
                type: 'spacer',
                size: 'md',
              },
              {
                type: 'text',
                text: 'Learn more [here](https://google.com)',
              },
              {
                type: 'checkbox',
                id: 'checkbox-2',
                // label: 'Select Label',
                required: true,
                placeholder: 'Select company size',
                options: [
                  {
                    id: 'option-1',
                    type: 'option',
                    required: true,
                    label: 'Accept Terms and conditions',
                  },
                ],
              },
            ],
          }                                        
})</script> 

Below, an example of a preview of how PrechatForm looks in the widget. User can customise the fields before starting the chat.

Other methods

User authentication with externalId

When the widget initializes, an anonymous customer is automatically created. This customer can then send messages to the bot.

In some scenarios, you would like to federate the customer identity with the ones of your website or application. This is done using the externalId. This field identifies the user on your system. It can be an email address, a username, a uuid or any other user id on your database. Most importantly it should be unique and always reference a entity from your system.

In order to proof the authenticity of the user, we require a signed JWT token that validates your ownership of the widget. Otherwise anyone can impersonate your users.

Create a signed JWT token

In order to create a signed JWT token:

  1. Login into your Chatlayer account.

  2. Create an access token at: https://app.chatlayer.ai/settings/api-access/tokens

  3. The token will have the form of [keyId]:[keySecret]. Notice there is : separating the two parts of the token.

  4. Implement server side code to sign new JWTs using thekeyId and keySecret. The JWT header must specify the key ID in the kid field. The JWT payload must include a channel_id claim in the jwt payload and a sub claim wich should be set to your external user id.

A node.js sample is provided below using jsonwebtoken >= 6.0.0:

var jwt = require('jsonwebtoken');
// given token 647f1ecd48f7f8aa3abe17fd:5e39a6051B53e7Cf92CF0dB9F2Bd5Eb0
var KEY_ID = '647f1ecd48f7f8aa3abe17fd';
var KEY_SECRET = '5e39a6051B53e7Cf92CF0dB9F2Bd5Eb0';
var CHANNEL_ID = 'liiq8woe:647f1f0910f7d21246e1df75';

var signJwt = function (userId) {
  return jwt.sign(
    {
      channel_id: CHANNEL_ID,
      sub: userId,
    },
    KEY_SECRET,
    {
      header: {
        alg: 'HS256',
        typ: 'JWT',
        kid: KEY_ID,
      },
    }
  );
};
  1. From your website, call:

Chatlayer.login(externalUserId, signedJWT).then(() => {
  // user logged in
  }, err => {
// error occurred
  })`

method

necessary info

Chatlayer.login()

(externalId: string, jwt: string)

Chatlayer.logout()

(externalId: string, jwt: string)

Delete the chat history

Our new widget, by default, stores all conversations between the bot and the customer. This ensures an experience akin to other messaging platforms. When users contact the bot through the widget and reopen it, they can view all past conversations by default.

If you want to circumvent this or want customers to be able to refresh the conversation, you could use our chatlayer.login or chatlayer.logout commands to allow you to do so.

Create a refresh button

The script below will allow you to add a button to your widget that when being clicked will clear the conversation. The button will have the id: RESTART_CONVERSATION and upon being clicked will logout the user and log them back in immediately.

The button itself (to add in header section):
  customActions: [
            {
              id: RESTART_CONVERSATION,
              image:
                "data:image/svg+xml,%3Csvg xmlns='' height='24' width='24'%3E%3Cpath d='M12 5V2L8 6l4 4V7c3.31 0 6 2.69 6 6 0 2.97-2.17 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93 0-4.42-3.58-8-8-8zM6 13c0-1.65.67-3.15 1.76-4.24L6.34 7.34A8.014 8.014 0 0 0 4 13c0 4.08 3.05 7.44 7 7.93v-2.02c-2.83-.48-5-2.94-5-5.91z' fill='white' /%3E%3C/svg%3E",
            },
          ]

Then in the snippet you placed in the bottom add:

Chatlayer.on('widget:custom_action', async ({ id }) => {
              console.log('widget:custom_action event handler callback', { id });
              if (id === RESTART_CONVERSATION) {
                await window.Chatlayer.logout();
                await window.Chatlayer.login();
              }
            });

Events send by Chatlayer

Chatlayer.on(event, (arg1, arg2) => ...)

event

description

arg1

widget:opened

The widget was opened

-

widget:closed

The widget was closed

-

widget:custom_action

When a custom action button was clicked

-

message:received

A message was received

-

message:sent

A message was send by the user

-

event:received

An event was received

EventPayload

init

The widget was initialized

-

destroy

The widget was destroyed

-

EventPayload

Field

Type

Description

generic_event

GenericEvent

A generic event

agent_joined_event

AgentJoinedEvent

When an agent joins the conversation

agent_left_event

AgentLeftEvent

When an agent leaves the conversation

GenericEvent

Field

Type

Description

payload

JSON

Arbitrary data set to the event. A valid JSON object.

Note that you can use the JSON builder to send generic events from your user's session to the site you've hosted the widget on.

AgentJoinedEvent

Field

Type

Description

agent

Agent

Represents an agent that is involved in a conversation.

Agent

Field

Type

Description

display_name

string

Agent's display name

picture_url

string

The Agent's picture url.

type

AgentType

Agent's classification can be UNKNOWN_AGENT_TYPE, HUMAN or BOT.

Use Chatlayer.off(event, (arg1, arg2) => ...)to unsubscribe from these events.

Change the language

Chatlayer.setLanguage(language)

Sets the current language. Only languages on the list of languages supported by your bot will be accepted.

Chatlayer.language

Is the current language on the widget.

Note that you can also change the bot's language using the iframe in the Installation tab.

Set the session data

If you want to transfer data from your website to the chatbot, you can add that data to the chatlayer function after initializing the widget. All data will be put in the Chatlayer session. This data can then be used to customize the chatbot flow, based on actual website data.

Chatlayer.setSessionData(SessionData)

Sets extra data in the conversation session and returns a promise

Example

Chatlayer.setSessionData({
  Product: 'iPhone XS',
  });
// or
Chatlayer.setSessionData('Product', 'iPhone XS');

The example above shows how you can set the variable Product in the Chatlayer session. It will get the value iPhone XS in this case.

Setting a delegate

The widget allows you to set a delegate to receive callbacks when important changes happen in the conversation. To set a delegate, pass the delegate parameter in to init options, or use the setDelegate method. The delegate object may optionally contain beforeDisplay or beforeSend functions.

Passing delegate as part of init options is the preferred method. The setDelegate method can be used to change or remove delegate behaviors after a conversation has been initialized.

const delegate = {
  beforeDisplay(message) {
    if (data.sender.type === 'agent') {
      message.sender.display_name = 'John Doe';
    }
    return message;
  },
  beforeSend(message) {
    return message;
  },
};
 
// Passing delegate as an init parameter
Chatlayer.init({
  channelId: '<channel-id>',
  delegate,
});
 
// Using setDelegate
Chatlayer.init({ integrationId: '<channel-id>' }).then(() => {
  Chatlayer.setDelegate(delegate);
});

DelegateConfig

DelegateConfig is an object containing the 2 fields below:

beforeDisplay

The beforeDisplay delegate allows a message to be hidden or modified before it is displayed in the conversation. This delegate should return a falsy value such as null to hide the message. It can also return a modified message object in order to change what the user will see rendered in their conversation history. Note that this change affects the client side rendering only; the server side copy of this message can not be modified by this delegate.

beforeSend

The beforeSend delegate method allows you to modify properties of a message before sending it to Chatlayer. The modified message must be returned for it to take effect.

A common usage of this method is to add message metadata.

Note that when a file or an image is uploaded, only the message metadata may be updated. Other message properties such as type or text won't be considered.


💬 Give feedback

Please let us know what you think of the new Web widget here.

Last updated