Chatlayer Documentation
Get in touchAbout Chatlayer
  • Welcome
  • What's new
  • Send feedback
  • start quickly
    • Leadzy tutorial
      • 0. Introduction
      • 1. New bot, new block
      • 2. Understand your users
      • 3. Collect and display user input
      • 4. Steer the conversation with Conditions
      • 5. Empower your bot with Actions
      • 6. Set up a channel and publish your bot
    • Templates
      • Banking
      • E-Commerce Returns
      • E-Bike Shop
      • E-Scooter Support
      • Feedback
      • Find Nearest Location
      • GPT
      • 🆕Gym
      • Job applications
      • Knowledge base AI template
      • Lead generation
      • 🆕NPS
      • Restaurant
      • Retail
  • navigation
    • Analytics
      • Dashboard
      • Customers
      • Conversations
      • User flow
      • Intents
      • 🆕Funnels [Beta]
    • Bot builder
      • Flows
        • Canvas functionalities
        • Collaborate with team members
        • Manage your flows
        • 🆕[Beta] Export and import flows
      • Bot dialogs view
      • Translations
      • Events
    • NLP
      • Dashboard
      • Intents
      • Expressions
      • Entities
      • Train
      • NLP settings
      • Improve
    • Knowledge base AI
      • Add content to your KBAI
      • Build your KBAI flow
      • Use your KBAI source URL in a button
      • Use tags to limit your KBAI content
      • 🆕Use Tables to store your KBAI questions
      • 🆕Manage handover where KBAI is unsatisfactory
    • History
      • Conversations
      • Execution logs
      • Versions
    • Channels
    • Tables
      • Create a table with records
      • Column types
      • Operate on your records
        • Insert record
        • Update record
        • Retrieve record
        • Delete record
      • API
    • Settings
      • Bot settings
      • Offloading
      • Variables
      • Voice
      • Import/Export
  • build your bot
    • Conversation design
      • Plan your bot
      • Conversation design workflow
    • Flow logic
      • Blocks
        • Message
        • Condition
        • Collect input
        • Action
      • Go-to connections
    • 🆕Emulator
    • Tips & best practices
      • Route your flow depending on the time
      • Improve the Not understood block
        • How to create better not understood messages
        • Not understood counter
        • Not understood Google search
      • Go to previous block
      • Recognizing a returning user
      • Skip introduction message
      • Route your flow depending on the channel
      • Reuse flows
      • Connect two bots to each other
  • understand users
    • Natural language processing (NLP)
      • Basic NLP concepts
      • Detect information with entities
        • Match entities
        • Contextual entities
        • System entities
        • Composite entities
      • NLP best practices
        • Word order and diversity of expressions
      • AI intent booster
      • Train your NLP
      • Context
      • NLP import & export
      • Sentiment analysis
    • Languages
      • Supported languages
      • Make your bot multilingual
      • Change language within the conversation
  • set up channels
    • Add a channel to your bot
    • All channels
      • 🚨Facebook Messenger [Deprecated soon]
        • Facebook Admin Removal
        • Facebook Webview Whitelisting
        • Facebook Messenger API updates for Europe
      • 🚨Google Assistant [Deprecated soon]
      • Webhook
      • Web
        • 🚨Web V1 [Deprecated]
          • Customize web widget
          • Live example web widget
        • 🆕Web V2
          • 🆕From Web V1 to V2
          • 🆕Web V2 methods and options
    • Sinch Conversation API
      • Configure your Sinch Conversation API
      • 🆕 Make the most of RCS with Carousels
      • WhatsApp Business API
  • integrate & code
    • API calls
      • Configure your API integration
      • Advanced API features
      • V1 API Reference
      • Custom integrations 101
    • Code editor
      • [Example] Sending data to Airtable (POST)
      • [Example] Retrieving data from Airtable (GET)
      • [Example] Making SOAP requests
    • App integrations
      • Airtable
      • Freshdesk
      • Freshdesk Messaging
      • 🆕Gmail
      • Intercom
      • Mailgun
      • OpenAI: GPT-3, ChatGPT and GPT-4
      • Salesforce
      • 🆕Slack
      • Topdesk
      • Zendesk Support
      • Zendesk Sunshine (beta)
    • 🆕Expression syntax
    • Human handover & live chat
      • Sinch Contact Pro
      • #Interact
      • Genesys Cloud
      • Offloading Webhook
      • Salesforce Service Cloud
      • Sparkcentral by Hootsuite
      • Zendesk Chat
    • Chatlayer messages specifications
  • Publish
    • Publish your bot
      • Publish a flow
  • Analyze & maintain
    • Analytics definitions
    • Data retention
    • Maintenance
    • Session
    • Track events for analytics
  • VOICE
    • 🆕Send bot response as audio
    • Voicebots
      • Create a voicebot
      • Voicebot-specific actions
      • Test your voicebot
      • From chat to voice
  • access & support
    • Identity & Access
      • Single Sign-On (SAML SSO)
    • Billing & subscription
    • Get in touch
    • Chatlayer glossary
    • SaaS Regions & IP Ranges
    • Status
    • Debug your bot
      • No correct response
      • Collect input not working
      • Video isn't working
Powered by GitBook
On this page
  • Creating your web chat widget
  • Whitelisting
  • Embedding the web widget on your website
  • Should I use SDK or iframe?
  • SDK
  • Iframe
  • Encryption
  • Live example

Was this helpful?

  1. set up channels
  2. All channels
  3. Web

Web V1 [Deprecated]

PreviousWebNextCustomize web widget

Last updated 4 months ago

Was this helpful?

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

Attention:

This article refers to our legacy web widget, which will be deprecated on 01/10/2024. On 01/04/2024, we're discontinuing support for Web chat widget V1. All newly created web widgets should follow the .

One of the most common ways of making a bot available to your clients is through a chat widget. In this technical guide, we will guide you through the process of integrating the bot in your website.

Creating your web chat widget

To create a chat widget for your bot, navigate to the Channels tab and then click on the pencil icon next to Web.

Click "+ Create" to start building your first custom chat widget.

You can create multiple chat widgets for one bot, remove them, view them, and copy them using the buttons in the chat widget table.

On the Chat Widget page you can customize a number of key chat widget components:

  • Config tab

    • Title of the bot

    • Template

    • Title font & font size

    • Paragraph font & font size

    • White listing of the domains you want the bot to be activated on (i.e. your own website domain and any other domains you use for testing)

    • Images (title, bot, user, send icon, SDK button - which is the image that's shown when the bot is closed)

  • Colors tab

    • Colors of all the key components of the chatbot

  • Translations tab

    • Translations for the default chat widget messages such as "Write reply..."

Whitelisting

To make sure your bot can only be activated on your website, all your chat widgets must be whitelisted before you can use them. To do this, go to the config tab of the Chat Widget builder and add a regular expression that matches the domain names that you wish to whitelist.

A simple example of this regex format for https://www.chatlayer.ai: ^https:\/\/www\.chatlayer\.ai(\/|$)

Whitelisting regexes can also be used for more complex, multi-domain configurations. Take the following set of domains as an example:^https:\/\/www\.(subdomain1|subdomain2)\.(rootdomain1|rootdomain2)\.com(\/|$) will whitelist the domains:

  • https://www.subdomain1.rootdomain1.com

  • https://www.subdomain1.rootdomain2.com

  • https://www.subdomain2.rootdomain1.com

  • https://www.subdomain2.rootdomain2.com

You can separate the alternatives by using a | character as follows:

^https:\/\/www\.subdomain1\.rootdomain1\.com(\/|$)|^https:\/\/www\.subdomain2\.rootdomain1\.com(\/|$)|^https:\/\/www\.subdomain1\.rootdomain2\.com(\/|$)|^https:\/\/www\.subdomain2\.rootdomain2\.com(\/|$)

A shorter regular expression which will match the same domains is:

^https:\/\/www\.(subdomain1|subdomain2)\.(rootdomain1|rootdomain2)\.com(\/|$)

Whitelisting with an iframe

Some browsers have a default referrerpolicy of strict-origin-when-cross-origin. This will enforce the browser to only include the origin of your webpage when it requests the content of an iframe.

If your iframe widget is hosted at https://example.com/chat_widget.html, requests will only contain the https://example.com/ portion of that path. This could cause issues if you use a whitelisting regex that matches the full path of your webpage, for example:

^https:\/\/example\.com\/chat_widget.html

If you want to use the full path of your webpage in the whitelisting configuration of your widget, you can override the referrerpolicy of the iframe that contains the link to your widget to be no-referrer-when-downgrade

<iframe referrerpolicy="no-referrer-when-downgrade" src="<CHATBOX_URL>"/>

Embedding the web widget on your website

To embed the bot on your website, start by clicking the Embed button in the top right of the Custom Chat Widget page.

There are two ways of integrating the Chat Widget on your website: you can use either iframe or SDK.

You can switch between SDK and iframe using the Type switcher above your widget:

Should I use SDK or iframe?

Our chat widget SDK is a layer on top of an iframe, which includes some other functionalities like a button that is shown before the chat window opens, with the option to close the chatbot.

If you want to get the chat widget onto your website with minimal custom development, it's best to use an SDK. The only thing you need to do is include a HTML script tag as described below.

If you want more control over other elements, such as the chat button, it's best to use iframe.

SDK

You can load the chat widget by using the script tag below. Calling the chatlayer function will show the button and your chat widget on the page.

<script src="https://chatbox.staging.chatlayer.ai/sdk/INSERT-TOKEN-HERE" 
        onload='chatlayer()' async>
    // The token can be found in the Chat Widget configuration window
</script>

Remove .staging from the URL if you want to integrate a LIVE bot. You can add parameters to the chatlayer function to include additional functionality.

<script src="https://chatbox.staging.chatlayer.ai/sdk/INSERT-TOKEN-HERE" 
        onload='chatlayer({"lang":"en","animation":"grow"})' async>
</script>

In this case, your bot will be opened in English, and when a user clicks the SDK button, it will be opened with the Grow animation.

SDK Options

Property name

Type

Remark

withCloseButton

boolean

The close button allows customers to close the bot clicking an "X" icon at the top right of the chat widget

autoOpen

boolean

noButton

boolean

session

object

Add data to the session which can be used to guide the flow.

sessionId

string

A session ID can be used to continue the conversation after the user has left the page. Make sure it's 20 characters or longer.

lang

string

Language of the bot

button

HTMLElement

wrapper

HTMLElement

Transferring a variable from your website, through the SDK to the chatbot

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

<script src="https://chatbox.staging.chatlayer.ai/sdk/INSERT-TOKEN-HERE"
 onload='chatlayer({session: {number: 1234, firstName: "User", lastName: "Name" }})' async>
</script>

Transferring the variables firstName and lastName to the SDK allows you to set the corresponding internal Chatlayer session variables. These specific variables decide how the user will show up in the Chatlayer conversations table.

internal: {
  ...
  user: {
      firstName: 'User',
      lastName: 'Name',
        },
        ...
    },
    ...
 session: {
     number: 1234,
     firstName: 'User',
     lastName: 'Name'
    }
    ...
    firstname: 'User',
    lastname: 'Name'
}

User authentication with the chat widget SDK

In a lot of cases it's required to know who is talking to the bot. One way to find out is by sending a login ID, detected on the website your user is logged in, and passing it on to the bot, when the SDK is initialized:

<script src="YOUR_CHATWIDGET_URL" 
onload='chatlayer({ sessionId: LoginID }})' async>
</script>

Chat widget button behaviour

If you import the chat widget with our SDK, you can decide when the widget opens or closes. An example:

var chatlayerChat = chatlayer({ lang: 'en'});
// This creates a Chatlayer.ai instance and adds the icon to your webpage

chatlayerChat.open();
// Opens the Chatlayer.ai chat window
setTimeout(()=>chatlayerChat.open(),10000)
// Opens the Chatlayer.ai chat window with a predefined delay
chatlayerChat.toggle();
// Toggles between the opened and closed version of the chat widget
chatlayerChat.close();
// Minimizes the chat widget window to the button

Make sure that the SDK script is loaded before running these functions.

Iframe

Embedding the chat widget in an iframe is the most straight forward embedding option. You determine how and where you place the element and you can style it as you like.

<iframe src="https://chatbox.staging.chatlayer.ai/INSERT-TOKEN-HERE?lang=en"/>

Remove .staging from the URL if you want to integrate a production bot. You can change ?lang=en to any language the bot supports.

Defining the sender ID

If you want to recognize a returning bot user, you can send a unique sender ID for each person opening the bot, which can then be used to open the same conversation when the page is reloaded.

<iframe src="https://chatbox.staging.chatlayer.ai/TOKEN?senderId=5241bbd5-6fd8-4333-85e0-72bsdf04f4c91"/>

Make sure that your sender ID is 20 characters or longer.

Transferring a variable from your website, through the iframe to the chatbot

The same goal can also be achieved by changing the iframe url:

<iframe src="https://chatbox.staging.chatlayer.ai/TOKEN?senderId=12345TEST&session[data][first_name]=Charlie"/>

The example above, would result in a session containing:

{
   "id":"1234TEST",
   "session":{
      "data":{
         "first_name":"Charlie"
      }
   }
}

Size and position of iframe

By adding the properties underneath to your CSS, you can resize the chat widget window. You can use these parameters to make the chat widget responsive for mobile devices.

<style>
    iframe.chatlayer-iframe {
        width: 350px
        max-width: 100%;
        max-height: 560px;
    }
</style>

Encryption

There are two main options for securing the chat widget. You can either verify the payload by using JWT, making sure it hasn't been tampered with, or you can encrypt the session created by the chat widget by using AES-256 data protection.

When you turn on the AES-256 data protection, you can only pass an encrypted token as the chat session. This token should be generated in your own back-end. The code to generate the token looks like this (using node.js):

const crypto = require('crypto');
const SECRET = 'CHATLAYER_TOKEN'
const createAESToken = (payload, secret = SECRET) => {
    const iv = Buffer.from(crypto.randomBytes(8)).toString('hex');
    const secretBuffer = Buffer.from(secret, 'hex');
    const cipher = crypto.createCipheriv('aes-256-cbc', secretBuffer, iv);
    const update = cipher.update(typeof payload === 'object' ? JSON.stringify(payload) : String(payload));
    const encrypted = Buffer.concat([update, cipher.final()]);
    return iv + encrypted.toString('hex');
};
const token = createAESToken({
    exp: Math.floor(Date.now() / 1000) + 36000,
    session: {
        isAuthorized: true
    },
    sessionId: 'UNIQUE_ID_FOR_THIS_USER'
});

How you pass this token to the client will depend on how you are generating your html, but this server-generated token should be what is passed to the chatlayer function:const chat = chatlayer({token: serverGeneratedToken});

Live example

We've created an example of how you can initialize and destroy the Chatlayer.ai chat widget through your own Javascript code.

<html>
  <head>
    <title>Chatlayer Events Example</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <button onclick="initChatlayer()">Initialize Chatlayer</button>
    <button onclick="destroyChatlayer()">Destroy Chatlayer</button>
    <br />
    <br />
    <button onclick="openChatlayer()">Open Chatlayer Widget</button>
    <button onclick="closeChatlayer()">Close Chatlayer Widget</button>

    <script>
      /**
       * This example showcases the destruction of a Chatlayer webwidget
       * by triggering the JSON builder plugin in the flow.
       *
       * The JSON builder action dialog was set up as follows:
       * https://minio.dev.chatlayer.ai/public/JSONBuilder.png
       *
       */

      let chatlayerInstance = null;

      const initChatlayer = () => {
        if (chatlayerInstance) return;
        console.log("Initializing the Chatlayer widget ...");
        chatlayerInstance = chatlayer({ lang: "en" });
        // Event types are "event", "open" and "close"

        chatlayerInstance.on("open", event => {
          console.log('OPENED');
        });

        chatlayerInstance.on("close", event => {
          console.log('CLOSED')
        });

        chatlayerInstance.on("event", event => {
          // Note the content of event here: the "action" key with value "destroy"
          // originates directly from the configured JSON Builder action.
          const isChatlayerDestroyEvent = event.action === "destroy";
          if (isChatlayerDestroyEvent) {
            destroyChatlayer();
          }
        });
      };

      const destroyChatlayer = () => {
        if (!chatlayerInstance) return;
        console.log("Destroying the Chatlayer widget ...");
        // To destroy the widget, it has to be opened first
        chatlayerInstance.open();
        chatlayerInstance.destroy();
        chatlayerInstance = null;
      };

      const openChatlayer = () => {
        if (!chatlayerInstance) {
          console.log("Please initialize Chatlayer first!");
          return;
        }
        chatlayerInstance.open();
      };

      const closeChatlayer = () => {
        if (!chatlayerInstance) {
          console.log("Please initialize Chatlayer first!");
          return;
        }
        chatlayerInstance.close();
      };
    </script>

    <!-- Note the absence of the onload prop on the following script tag. -->
    <!-- To automatically initialize the webwidget, you would add the prop: -->
    <!-- onload="initChatlayer()" -->
    <script
      src="https://chatbox.staging.chatlayer.ai/sdk/5ecbcf1514c3dc4942f05f96"
      async
    ></script>
  </body>
</html>

JSON builder plugin configuration:

As you can see from the example above, you can initialize the widget, open/close it, as well as destroy it from your own code. The example shows you how to use the JSON Builder plugin to trigger a destroy event for the chat widget.

Upload custom CSS (more information about custom CSS )

An easy way to validate your regular expression is by using online tools like

More information about referrer policies can be found .

This login ID can later be reused to perform calls with the .

A user's session can be updated at any time through the API call.

View a live version of this code .

🚨
here
https://regex101.com/
here
API plugin
Send messages through a Webhook channel
here
new web widget, Web V2
moving from V1 to V2
Web V2 documentation