Platform
APIs & SDKs
Resources

...

Chat Widget JS API

Introduction

About the API

The Chat Widget JavaScript API lets you interact with the Chat Widget embedded on your site. It might come in handy whenever you want to gather some additional data using LiveChat, show or hide your Chat Widget on certain occasions, or amend its behavior in a way that is not provided by the standard settings.

This document focuses on Developers and requires a basic knowledge of JavaScript. However, if you would have any questions, don't hesitate to start a chat with our Support Team or add a new topic on our Discord for Developers.

Getting started

The API is accessed through the LiveChatWidget object. It is being initialized within the LiveChat tracking code, which is used to install our Chat Widget on your site. If you haven't installed the code yet, you can either find it directly in the LiveChat app or copy it from here (remember to replace <LICENSE_NUMBER> with your license number):

LIVECHAT TRACKING CODE
Copied!
<!-- Start of LiveChat (www.livechat.com) code -->
<script>
  window.__lc = window.__lc || {};
  window.__lc.license = <LICENSE_NUMBER>;
  ;(function(n,t,c){function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},once:function(){i(["once",c.call(arguments)])},off:function(){i(["off",c.call(arguments)])},get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},call:function(){i(["call",c.call(arguments)])},init:function(){var n=t.createElement("script");n.async=!0,n.type="text/javascript",n.src="https://cdn.livechatinc.com/tracking.js",t.head.appendChild(n)}};!n.__lc.asyncInit&&e.init(),n.LiveChatWidget=n.LiveChatWidget||e}(window,document,[].slice))
</script>
<noscript
  ><a href="https://www.livechat.com/chat-with/<LICENSE_NUMBER>/" rel="nofollow"
    >Chat with us</a
  >, powered by
  <a
    href="https://www.livechat.com/?welcome"
    rel="noopener nofollow"
    target="_blank"
    >LiveChat</a
  ></noscript
>
<!-- End of LiveChat code -->

The API requires the newest version of the code snippet (≥2.0). If you had installed the code a while ago and the API presented here doesn't work, you should either update the code or use the old version of JS API. You can check the current version of your snippet by calling the scriptTagVersion function:

scriptTagVersion
Copied!
LiveChatWidget.scriptTagVersion();

The LiveChatWidget object comes with four functions:

  • on registers a callback function for a specific event
  • once similar to on but after single event trigger the callback is removed
  • off removes a callback registered by on
  • call allows you to invoke methods and setters
  • get makes it possible to fetch data

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

LiveChatWidget.function("method", "data");

For example, if you would like to set your customer's name to John Doe, this is how it would look like:

LiveChatWidget.call("set_customer_name", "John Doe");

Asynchronous Initialization

Asynchronous initialization is an optional feature available for Chat Widget via JavaScript API. It allows for far more control over the moment when the Chat Widget should be loaded. It can be especially useful if you would like to make widget initialization happen as a consequence of some user interaction, or your own application business logic event.

This feature is disabled by default, so the Chat Widget loads automatically just after the snippet code is executed. In order to enable it, you need to explicitly set __lc.asyncInit property to true.

<!-- Start of LiveChat (www.livechatinc.com) code -->
<script>
  window.__lc = window.__lc || {};
  window.__lc.license = <LICENSE_NUMBER>;
  // Add the following line after your LiveChat license number
  window.__lc.asyncInit = true;

  /* rest of the standard snippet code */
</script>
<!-- End of LiveChat code -->

From now on the snippet code will be executed but the Chat Widget and its resources will not be loaded. It means that although you will have access to LiveChatWidget object, the widget itself will not be present on your website and the ready callback will not be triggered.

Later in your code you can initialize Chat Widget manually when needed. To do that simply call init function from LiveChatWidget object.

LiveChatWidget.init()

Methods

JS API methods allow you to create custom ways to interact with a widget. For example, you can hide your widget based on specific conditions or trigger a sales tracker defined earlier in the LiveChat application.

Here's the list of available methods:

Maximize

It maximizes the Chat Widget.

Example
LiveChatWidget.call("maximize");

To maximize the Chat Widget and pre-fill the chat input field with a predefined message, you can use the optional messageDraft param.

LiveChatWidget.call("maximize", { messageDraft: "I need help!" });

This method maximizes the Chat Widget and automatically inserts "I need help!" into the chat input field. If a Pre-chat form is enabled, it instead creates a message draft that is sent when the form is submitted.

The action will have no effect if the widget's current state prevents message entry or if the user already has a message draft.

Minimize

It minimizes the Chat Widget.

Example
LiveChatWidget.call("minimize");

Hide

It hides the Chat Widget on the site. You will need to use either 'maximize', or 'minimize' API calls to show it afterwards.

Example
LiveChatWidget.call("hide");

Destroy

It destroys the Chat Widget. It won't be available for further actions until the window is refreshed.

Example
LiveChatWidget.call("destroy");

Hide greeting

It hides the currently displayed greeting. In order to hide particular greeting you can listen to new_event or greeting_hidden callbacks to know when greeting with specified id or uniqueId appears and disappears accordingly.

Example
LiveChatWidget.call("hide_greeting");

Trigger sales tracker

It triggers a sales tracker created in the LiveChat application and passes over data about a sale. The data is then visible in LiveChat's Reports and Archives. For more information about how Sales Tracker works and how to set it up on your website, check out our official Help Center article: How Sales Tracker works in practice.

Example
LiveChatWidget.call("trigger_sales_tracker", {
  trackerId: "V9x4nEIlFPhblkHW9qIOGLakMXen5NS0",
  orderPrice: total_order_price,
  orderId: order_number,
});
Payload
paramtypedescription
trackerId*stringthe Chat Widget state
orderPricestringCustomer data from the Chat Widget
orderIdstringCustomer data from the Chat Widget

*required – trackerId can be obtained after creating a sales tracker in LiveChat application

Getters

You can use getters to fetch the data from the Chat Widget.

Available getters:

Get state

It returns the Chat Widget state. This includes Widget visibility and license availability.

Example
LiveChatWidget.get("state");
Response
paramtypedescription
availability'online' | 'offline'Group's availability
visibility'maximized' | 'minimized' | 'hidden'the Chat Widget visibility

Get customer data

It returns a filtered list of customer data.

Example
LiveChatWidget.get("customer_data");
Response
paramtypedescription
idstringunique customer id
namestringcustomer name, as provided
emailstringcustomer e-mail address, as provided
isReturningbooleanif this customer visited you before
status'queued' | 'chatting' | 'browsing' | 'invited'Customer's status
sessionVariablesRecord<string, string>additional free-form session information

Get chat data

It returns chat data which contains current chat and thread ids.

Example
LiveChatWidget.get("chat_data");
Response
paramtypedescription
chatIdstringunique chat id
threadIdstringunique current thread id

Setters

Various data can be sent over to the LiveChat integration so that your Agents can use it. For more information, you can read these articles in our Help Center: https://www.livechat.com/help/custom-variables-configuration/.

Available setters:

Set session variables

Creates new session variables, or replaces the ones set previously.

LiveChatWidget.call("set_session_variables", {
  username: "john.doe",
  cart_value: "450",
  "order date": "05/21/2019",
});

Update session variables

It changes the values of your session variables. Please note that the existing variables won't be replaced. The new session variables will be included together with the ones set previously.

Example
LiveChatWidget.call("update_session_variables", {
  username: "j.doe",
  cart_value: "400",
  "order date": "06/15/2019",
});

Set customer name

It sets the customer's name.

Example
LiveChatWidget.call("set_customer_name", "John Doe");

Set customer email

It sets the customer's email address.

Example
LiveChatWidget.call("set_customer_email", "john@example.com");

Callbacks

Callbacks allow you to react to the events triggered by the Chat Widget. You can use them to add custom behaviors when certain events happen. This can be accomplished by subscribing a callback with the API.

Available callbacks:

On ready

The Chat Widget has finished loading. If the Chat Widget is already loaded the provided handler function will be called immediately. With this callback, you will receive the Chat Widget state and customer data as if requested by their getters.

Payload
paramtypedescription
stateWidgetStatethe Chat Widget state
customerDataCustomerDataCustomer data from the Chat Widget
function onReady(initialData) {
  // Chat Widget is ready

  var state = initialData.state;
  var customerData = initialData.customerData;
}

LiveChatWidget.on('ready', onReady)
// LiveChatWidget.off('ready', onReady)

On availability changed

Availability has changed for the current group.

Payload
paramtypedescription
availability"online" | "offline"Availability of a group
function onAvailabilityChanged(data) {
  if (data.availability === "online") {
    // we're available to chat!
  } else {
    // sadly, no agents are available at the moment.
  }
}

LiveChatWidget.on('availability_changed', onAvailabilityChanged)
// LiveChatWidget.off('availability_changed', onAvailabilityChanged)

On visibility changed

It is called once the visibility of the Chat Widget has changed. This applies to both user actions like maximizing or minimizing the window as well as hiding or showing the Chat Widget through the use of this API.

Payload
paramtypedescription
visibility"maximized" | "minimized" | "hidden"the Chat Widget visibility
function onVisibilityChanged(data) {
  switch (data.visibility) {
    case "maximized":
      break;
    case "minimized":
      break;
    case "hidden":
      break;
  }
}

LiveChatWidget.on('visibility_changed', onVisibilityChanged)
// LiveChatWidget.off('visibility_changed', onVisibilityChanged)

On customer status changed

It is called once the status of your customer has changed. This can be used to track the following info:

  • If and when Customers are being invited to chat
  • If Customers are already chatting
  • If they are waiting for an agent to become available in the queue
Payload
paramtypedescription
status'queued' | 'chatting' | 'invited' |'browsing'Customer's status
function onCustomerStatusChanged(data) {
  switch (data.status) {
    case "queued":
      // customer is in queue
      break;
    case "chatting":
      // customer is currently chatting
      break;
    case "invited":
      // customer received an invitation but didn't start the chat
      break;
    case "browsing":
      // customer is in idle state, not queued, not chatting, and didn't receive an invitation
      break;
  }
}

LiveChatWidget.on('customer_status_changed', onCustomerStatusChanged)
// LiveChatWidget.off('customer_status_changed', onCustomerStatusChanged)

On new event

It is called for both incoming and outgoing events.

Payload
paramtypedescription
timestampnumberEvent's send timestamp
type'message' | 'rich_message' | 'file'Event's type
author.idstringEvent's author id
author.type'customer' | 'agent'Event's author type
If new event is a greeting:
greeting.idnumberGreeting's template id
greeting.uniqueIdstringGreeting's event uniqueId
function onNewEvent(event) {
  switch (event.type) {
    case "message":
      // handle new message event
      break;

    case "rich_message":
      // handle new rich_message event
      break;

    case "file":
      // handle new file event
      break;

    default:
      break;
  }

  if (event.greeting) {
    // new event is a greeting
    // greeting properties are available
    var id = greeting.id;
    var uniqueId = greeting.uniqueId;
  }
}

LiveChatWidget.on('new_event', onNewEvent)
// LiveChatWidget.off('new_event', onNewEvent)

On form submitted

It is called after a form has been submitted in the chat.

Payload:

paramtypedescription
type"prechat" | "postchat" | "ticket"Form's type
function onFormSubmitted(data) {
  switch (data.type) {
    case "prechat":
      // prechat submitted
      break;

    case "postchat":
      // postchat submitted
      break;

    case "ticket":
      // ticket submitted
      break;

    default:
      break;
  }
}

LiveChatWidget.on('form_submitted', onFormSubmitted)
// LiveChatWidget.off('form_submitted', onFormSubmitted)

On rating submitted

It is called after the customer has rated the chat, or cancelled the previous rating.

Payload
paramtypedescription
value"good" | "bad" | "none"Customer's rating value
function onRatingSubmitted(value) {
  // do something
}

LiveChatWidget.on('rating_submitted', onRatingSubmitted)
// LiveChatWidget.off('rating_submitted', onRatingSubmitted)

On greeting displayed

It is called after the greeting has been displayed to the customer.

Payload
paramtypedescription
idnumberGreeting's template id
uniqueIdstringGreeting's event uniqueId
function onGreetingDisplayed(greeting) {
  // greeting has been displayed
  var id = greeting.id;
  var uniqueId = greeting.uniqueId;
}

LiveChatWidget.on('greeting_displayed', onGreetingDisplayed)
// LiveChatWidget.off('greeting_displayed', onGreetingDisplayed)

On greeting hidden

It is called after the greeting has been cancelled by the customer or hide_greeting method.

Payload
paramtypedescription
idnumberGreeting's template id
uniqueIdstringGreeting's event uniqueId
function onGreetingHidden(greeting) {
  // greeting has been hidden
  var id = greeting.id;
  var uniqueId = greeting.uniqueId;
}

LiveChatWidget.on('greeting_hidden', onGreetingHidden)
// LiveChatWidget.off('greeting_hidden', onGreetingHidden)

On rich message button clicked

It is called after the rich message button has been clicked by the customer.

Payload
paramtypedescription
eventIdstringButton's owner event's id
postbackIdstringClicked button's postback id
If button was included in greeting event:
greeting.idnumberGreeting's template id
greeting.uniqueIdstringGreeting's event uniqueId
function onRichMessageButtonClicked(data) {
  // rich message button clicked
  var eventId = data.eventId;
  var postbackId = data.postbackId;

  if (data.greeting) {
    // clicked button belongs to greeting event
    var greetingId = data.greeting.id;
    var greetingUniqueId = data.greeting.uniqueId;
  }
}

LiveChatWidget.on('rich_message_button_clicked', onRichMessageButtonClicked)
// LiveChatWidget.off('rich_message_button_clicked', onRichMessageButtonClicked)

Playground

Here's where you can play with the Chat Widget JavaScript API in an interactive environment. Use the buttons and inputs on the left side of the Widget or try to invoke some functions directly in the console.

Examples

Here you can find some example usage of the Chat Widget JavaScript API. They all require the Widget to be installed on the page and window.LiveChatWidget to be defined.

Show the Widget after time

Show the Chat Widget after 30 seconds and keep it open after reloading.

LiveChatWidget.on("visibility_changed", function(data) {
  if (data.visibility === "maximized") {
    localStorage.setItem("livechat_chat_visible", true);
  }
});

var isWidgetVisible = Boolean(localStorage.getItem("livechat_chat_visible"));

if (!isWidgetVisible) {
  setTimeout(function() {
    LiveChatWidget.call("maximize");
  }, 30000);
}

Open the Widget using the button

Show the hidden or minimized Widget after a button has been clicked. You can change the Widget visibility as described in our Help Center

var chatButton = document.getElementById("chat-btn");
chatButton.addEventListener("click", function() {
  LiveChatWidget.call("maximize");
});

Prefill username and email

It sets the Customers name and email using their login and email.

var user = JSON.parse(localStorage.getItem("user"));

LiveChatWidget.call("set_customer_name", user.login);
LiveChatWidget.call("set_customer_email", user.email);

Initialize Widget asynchronusly on button click

Initialize Chat Widget after clicking the button.

<html>
  <head>
    <!-- Start of LiveChat (www.livechatinc.com) code -->
    <script>
      window.__lc = window.__lc || {};
      window.__lc.license = <LICENSE_NUMBER>;
      window.__lc.asyncInit = true;

      /* rest of the standard snippet code */
    </script>
    <!-- End of LiveChat code -->
  </head>
  <body>
    <button id="chat-btn">Chat with us!</button>
    <script>
      var chatButton = document.getElementById('chat-btn');
      chatButton.addEventListener('click', function() {
        // Initialize Chat Widget
        LiveChatWidget.init();
      })      
    </script>
  </body>
</html>

...

Join the community
Get in direct contact with us through Discord.
Follow us
Follow our insightful tweets and interact with our content.
Contribute
See something that's wrong or unclear? Submit a pull request.
Contact us
Want to share feedback? Reach us at: developers@text.com