Chatlio widget API

If you want your own web app to control and interact with your Chatlio widget you can use the Chatlio API features described below.

READ FIRST

  1. For best results, wrap all api calls in chatlio.ready documented below.
  2. Make sure you are always using the latest embed code found here.

Overview

When your web page loads, the Chatlio widget initializes itself and contacts the Chatlio server to fetch meta data, such as your team’s online status, customized text for the widget UI and other configuration data. What this means in practice is the widget markup is not available immediately on page load, but inserted after Chatlio finishes loading.

The API is designed in such a way as to let you execute code without waiting for Chatlio to initialize, instead queueing up API calls and execute them as soon as possible.

Use the global object window._chatlio to make API calls.

When using the API to control when and how to display Chatlio, it can be useful to provide an extra attribute to the widget initialization code to force the widget to stay out of the way until your own code summons it: data-start-hidden . Add this to your embed code:

  n.setAttribute('data-start-hidden', true);

Custom events

The Chatlio widget will emit events to help you integrate it more tightly into your own website.

Ready

When the Chatlio widget has finished loading and initializing the data it needs it emits a custom event, chatlio.ready . Your code can listen for this and execute your own code at the right time.

The chatlio.ready event is emitted when the widget has a DOM node and have successfully registered with Chatlio (which in turn opens channels and sockets sets everything up for chatting). For instance, you can detach the widget DOM node and move it to wherever you please in your DOM tree. You can also use the API freely, calling e.g. _chatlio.show() . This event is guaranteed to emit once per page load.

Example:

  document.addEventListener('chatlio.ready', function (e) {
    console.log("[chatlio.ready] e: %o", e);
    var chatlioNode = e.target;
    console.log("[chatlio.ready] widget DOM node: %s (children: %d)", chatlioNode, chatlioNode.childNodes.length);
    // Remove chatlio and stick it somewhere else:
    document.getElementById("otherContainer")
      .appendChild(chatlioNode.parentNode.removeChild(chatlioNode));

    // It's safe to use the API of course
    _chatlio.show();
  }, false);

firstMessageSent

When the visitor sends their first message to you, effectively initiating a new chat, the chatlio.firstMessageSent event is emitted.

Example:

  document.addEventListener("chatlio.firstMessageSent", function(event){
    console.log("[chatlio.firstMessageSent] event: %o", event); // Do something interesting
  });

messageSent

When the visitor sends a message, the chatlio.messageSent event is emitted. The data payload contains the message data.

Example:

  document.addEventListener("chatlio.messageSent", function(event){
    console.log("[chatlio.messageSent] event: %o", event); // Do something interesting
  });

messageReceived

When the widget receives a message from Slack, the chatlio.messageReceived event is emitted. The data payload contains the message data, including the Slack channel ID of the conversation.

Example:

document.addEventListener("chatlio.messageReceived", function(event){
    console.log("[chatlio.messageReceived] event: %o", event); // Do something interesting
  });

preChatInfoSubmitted

When the visitors submits the pre-chat (ask for name & email) form, the chatlio.preChatInfoSubmitted event is emitted. The data payload contains the email address and name.

Example:

document.addEventListener("chatlio.preChatInfoSubmitted", function(event){
  console.log("[chatlio.preChatInfoSubmitted] event: %o", event.data); // Do something interesting
});

visibilityChange

When the widget visibility is changed we emit this event. In addition to other meta data, we emit the “visibility” state as “open” or “closed”. We also emit on first load. Useful when creating your own button to control Chatlio. See “style of widget when closed” option in the dashboard for more info on how to use.

Example:

  document.addEventListener("chatlio.visibilityChange", function(event){
    console.log("[chatlio.visibilityChange] event: %o", event); // Do something interesting
  });

collapsed

When the widget is collapsed the chatlio.collapsed event is emitted.

Example:

  document.addEventListener("chatlio.collapsed", function(event){
    console.log("[chatlio.collapsed] The widget is now minified"); // Do something interesting
  });

expanded

When the widget is expanded the chatlio.expanded event is emitted. Note: this even is not fired when using the API to show the widget in expanded mode with _chatlio.show({expanded: true}).

Example:

  document.addEventListener("chatlio.expanded", function(event){
    console.log("[chatlio.expanded] The widget is now expanded, maybe we'll get a message soon?");
  });

trigger

When the widget fires a triggered message the chatlio.trigger event is emitted.

Example:

  document.addEventListener("chatlio.trigger", function(event){
    console.log("[chatlio.trigger] The widget fired a trigger event: %o", event);
  });

offline

When the widget transitions to offline the chatlio.offline event is emitted.

Example:

  document.addEventListener("chatlio.offline", function(event){
    console.log("[chatlio.offline] The widget has went offline");
  });

online

When the widget transitions to online the chatlio.online event is emitted.

Example:

  document.addEventListener("chatlio.online", function(event){
    console.log("[chatlio.online] The widget has went online");
  });

conversationEnded

When the visitor or the operator ends the chat, the following event is emitted. The event payload looks like the following:

{endedBy: "operator", conversationUUID: <conversation UUID>}

Example:

  document.addEventListener("chatlio.conversationEnded", function(event){
    console.log("[chatlio.conversationEnded] The widget fired a conversationEnded event: %o", event);
  });

clearMessagesOnEnd

By default when the visitor or the operator ends the chat, the message history is cleared. You can prevent this using _chatlio.configure()

Example:

_chatlio.configure({clearMessagesOnEnd: false});


API methods

identify()

Use _chatlio.identify() to send information about the visitor to your site to Chatlio. This information will be displayed in Slack with the initial message they send, giving your team an easy way to contextualize the visitor.

The first param should be a unique string that identifies the visitor, like user ID or email.

The second param is a hash of your own custom data that will be printed in Slack when visitor starts a conversation. We also give special treatment to “name” and “email” params. See below.

Example:

  _chatlio.identify('user1234', {
    name: 'Elvis Presley',
    email: 'elvis@graceland.com',
    plan: 'king',
    favoriteColor: 'black'
  });

Chatlio uses the data you pass in to name the Slack channels. We name the channel based on this following:

  • If we find “name” param, we use that for channel name, eg. #z-amy-smith-123
  • Else we find “email” param, we use that for channel name, eg. #z-asmith-gmail-com-123
  • Else we use userId for channel name, eg. #z-user1234
  • If identify() is not used, we name channel after geo-location, eg. #z-san-francisco-ca-usa-123

isShown()

Returns a boolean, true when Chatlio is available and showing on screen, false when Chatlio is hidden or not yet initialized.

Example:

  if(_chatlio.isShown()){ alert("Thanks for chatting!"); }

open()

Open the widget expanded. Alias for _chatlio.show({expanded: true});

Here’s how you could attach a click handler to a button to open the Chatlio widget:

  <button onclick="_chatlio.open();">Open Chat</button>

show()

Show the widget on screen. If Chatlio is not yet initialized, the widget will be shown after a short delay.

Here’s how you could attach a click handler to a button to make the Chatlio widget visible:

  <button onclick="_chatlio.show();">Unhide Chat</button>

If you want the widget to show fully expanded or collapsed, regardless if the user clicked on the title bar of the widget, pass in an options object to set the expanded property to your preference.

Example:

  _chatlio.show({expanded: true});

Example:

  _chatlio.show({expanded: false});

Example Use Case:  Open widget with button or link

See the Pen Example use: open Chatlio widget with button by Chatlio (@chatlio) on CodePen.

hide()

Hide the widget.

Here’s how you could attach a click handler to a button to hide the Chatlio widget:

  <button onclick="_chatlio.hide();">Hide Chat</button>

showOrHide()

showOrHide toggles the widget visibility from shown or hidden. Useful when creating your own button to control Chatlio. See “style of widget when closed” option in the dashboard for more info on how to use.

Here’s how you could attach a click handler to a button to showOrHide the Chatlio widget:

  <button onclick="_chatlio.showOrHide();">Toggle Chat Visibility</button>

isOnline()

Returns a boolean, true when Chatlio is connected to the backend (even if it is not currently showing on screen) and there is somebody available on your Slack team to reply to chats.

Example:

  if(_chatlio.isOnline()){
    alert("It's on! Chat away!");
  }

configure()

Dynamically set configuration options for the widget. Useful for multi-language support or to dynamically set label text from javascript. Any attributes you omit will be set from data you configure in the Chatlio web UI.

NOTE: when you run _chatlio.reset() the data set through _chatlio.configure() is also reset. If this is undesirable to you, run the configure call again.

Example:

  _chatlio.configure({  
     "off":false,
     "maxVisitorInactiveMins":3,
     "noAnswerWithEmail": "Oops! Sorry no one has responded yet. We have your email on file if you need to leave or you can continue to wait.",
     "noAnswerWithoutEmail": "Oops! Sorry no one has responded yet. We have your email on file if you need to leave or you can continue to wait.",
     "status":"online",
     "hideWhenOffline":false,
     "showAvatarPreChat":false,
     "showTeamAvatarPreChat":false,
     "newMsgNotifications":true,
     "playSound":true,
     "dialogflowOn":false,
     "watsonconvOn":false,
     "activeAgentAvatar":"",
     "forwardSlackUserName":false,
     "widgetAlignment":"bottomRight",
     "titleColor":"#3f51b5",
     "titleFontColor":"#fff",
     "onlineTitle":"How can we help you?",
     "offlineTitle":"Contact Us",
     "agentLabel":"Support",
     "browserSideAuthorLabel":"",
     "onlineMessagePlaceholder":"Type message here...",
     "whiteLabel":false,
     "trackPresence":false,
     "offlineGreeting":"Sorry we are away, but we would love to hear from you and chat soon!",
     "offlineEmailPlaceholder":"Email",
     "offlineMessagePlaceholder":"Your message here",
     "offlineNamePlaceholder":"Name (optional but helpful)",
     "offlineSendButton":"Send",
     "offlineThankYouMessage":"Thanks for your message. We will be in touch soon!",
     "requireInfo":false,
     "requireInfoGreeting":"Enter your name and email to start chatting!",
     "requireInfoSubmitBtn":"Start",
     "requestScreenshotText":"Operator would like to take a screenshot of your browser. Confirm below.",
     "requestScreenshotAllowLabel":"Take screenshot",
     "requestScreenshotDeclineLabel":"Decline",
     "teamAvatarOn":false,
     "collapsedMode":"chip",
     "defaultOkBtnLabel":"Ok",
     "defaultSendBtnLabel":"Send",
     "defaultCancelBtnLabel":"Cancel",
     "defaultYesBtnLabel":"Yes",
     "defaultNoBtnLabel":"No",
     "showConversationEnd":true,
     "showConversationRating":true,
     "showTranscriptSendOpt":true,
     "clearMessagesOnEnd":false,
     "conversationEndLabel":"Your chat session has ended. Thanks for chatting!",
     "conversationRatingLabel":"How would you rate this chat?",
     "conversationRatingThankYou":"Thanks for rating your chat session!",
     "conversationRatingPlaceholder":"How can we improve?",
     "conversationEndTranscriptPlaceholder":"Email to send transcript of chat",
     "conversationEndConfirmationQuestion":"Are you sure you want to end this chat?",
     "conversationTranscriptSentThankYou":"Thanks! You will receive your transcript shortly.",
     "conversationEndMenuLinkLabel":"End Chat",
     "blacklistedUrls":"",
     "triggerJson":"",
     "useSgmt":false,
     "autoResponseMessage":"Question? Just type it below and we are online and ready to answer."
  });

Note: you can check most up to date list by looking at https://api-cdn.chatlio.com/v1/p/chat_endpoints/[your widget id]

You can configure the time-related strings Chatlio uses in the messages list to your locale like this:

  _chatlio.configure({
    timeLocale: {
      "just now": "juste maintenant",
      "y ago":    " ans",
      "mo ago":   " mois",
      "d ago":    " jours",
      "h ago":    " heures",
      "m ago":    " minutes"      
    }
  });

reset()

Reset the Chatlio widget and issue a new visitor UUID.

Sometimes you want to reset the Chatlio widget and prepare it for a new chat. You can also pass in options to restore a previous chat session.

Example:

  _chatlio.reset();

Example: reset Chatlio and show it in the expanded state

  _chatlio.reset({isClosed: false});

Example: reset Chatlio with a visitor UUID from a previous session

  // Get yours with _chatlio.vsUuid()
  _chatlio.reset({vsUuid: "fa7fbf68-c0df-7c1e-9a77-cee5c19242e3"});

Example: reset Chatlio with a visitor UUID from a previous session, with messages

  _chatlio.reset({
    vsUuid: "fa7fbf68-c0df-7c1e-9a77-cee5c19242e3",
    messages: [
      {body: "HELLO", author: "You"},
      {body: "Hi there! How can I help?", author: "Chatlio support"}
      ]
    }
  );

clearHistory()

Permanently remove all chat history from the current session while keeping the visitor session active.

If you need to clear a visitors message history without resetting the session entirely you can use _chatlio.clearHistory(). The operator in Slack will still see the full message history.

Example:

  _chatlio.clearHistory();

switchWidget()

If you have more than one Chatlio widget, each connected to its own Slack channel and need to switch between them on the same page, use _chatlio.switchWidget() and pass the UUID for the widget you want to switch to. Perhaps you’re building a custom UI to let your visitors select between different support teams and want to let them connect to the right people at the click of a button?

Example:

  var button = document.querySelectorAll("#some-selector")[0];
  button.addEventListener("click", () => {
    _chatlio.switchWidget("abc123ab-abc1-234a-bcd1-234abcd123ab");
  });

send()

Send a message to Slack from the browser.

If you need to send a message from the browser to Slack you can use _chatlio.send(). The message sent is indistinguishable from a normal message from the visitor and will show up in their widget chat history. If no previous messages were sent, _chatlio.send() will start a new conversation in Slack.

Example:

  _chatlio.send("This message is sent programmatically");

NOTE: _chatlio.send() will not work if the Chatlio widget has not been rendered, e.g. if data-start-hidden is set to true and before you called _chatlio.show() yet. If you want to send a message in this situation, use _chatlio.show().send("hello world").

page()

Tell Chatlio about a dynamic page change so chatlio will know current page and evaluate triggers for auto messaging.

NOTE: Only useful for customers using single page apps (React, Angular, Meteor, etc) that do not emit onpopstate event on route change.

Chatlio does try to detect page changes by monitoring the onpopstate event. But that doesn’t work for all javascript routing libraries. In that case, we recommend you call _chatlio.page() from your app when a route changes.

If you aren’t sure whether Chatlio is detecting your SPA page changes, check with _chatlio.debug().

Tell Chatlio about a page change:

  _chatlio.page();

trigger()

Programattically fire “triggered” messages like you can setup here. https://chatlio.com/app/#/settings/triggers

Assuming you have your own logic for a shouldShowTriggerHere() function, see following example.

if (shouldShowTriggerHere()) {
  _chatlio.trigger({message: "Help is available!", after: 0});
}

Note: You can only fire one trigger per hour, and triggers with a uid that has been seen before by visitor will not be shown.

_chatlio.trigger() takes the following arguments.

{
  message: "automessage text here",
  after: 30, // seconds
  uid: "optional-uid-string-here"
}

fullScreen()

We do our best to show the widget in the best manner for the device resolution, but sometimes you may want to force full screen mode on chat widget when expanded, example Phablets.

This is an example of how you can force expanded mode to be full screen and then disable if you want. This does not persist so you must call it on each widget render.

document.addEventListener('chatlio.ready', function (e) {
  var deviceNeedsFullScreen = true; // put your logic here.

  if (deviceNeessFullScreen) {
    // force full screen when expanded (required after each load, not persistent)
    _chatlio.fullScreen();

     // probably don't need this option, but in case you do.
    setTimeout(function(){
      console.log("disable full screen after 5secs");
      // disable full screen when expanded
      _chatlio.exitFullScreen();
    },5000);
  }

}, false);

debug

In order to help debug triggers and future Chatlio features, we have added a way to output debugging logs in the developer console.

To turn it on site wide, update your embed code with data-chatlio-debug attribute.

<script type="text/javascript">
    // embed code cut for brevity
    n.setAttribute('data-widget-id','<your widget ID here>');
    n.setAttribute('data-chatlio-debug', true); // <–– ADD THIS
    c.parentNode.insertBefore(n,c);
  }();
</script>

To turn it on temporarily.

  _chatlio.configure({debug: true});
:(
Your browser is out-of-date!

This website is built using latest technogies. Unfortunately your browser doesn't support those. Please update your browser to view this website correctly. Thank you.Update my browser now