The Gist JavaScript API

Avatar

By Jitta

updated about 1 month ago

The Gist JavaScript library provides a global object, gist, which responds to a few methods that allow you to update users without a page refresh and interact with the Messenger programmatically.

This document covers the following API Methods:

  1. Identify Leads and Users
  2. Track Custom Events
  3. Check If Gist Chat API Is Ready
  4. Change the width of Messenger Widget
  5. Hide the Messenger Widget
  6. Show the Messenger Widget
  7. Open the Messenger Widget
  8. Close the Messenger Widget
  9. Show the Messenger Launcher
  10. Hide the Messenger Launcher
  11. Change the layout of the Messenger
  12. Clear session cookies for logged-out users
  13. Callback when unread messages count changes
  14. Navigate to a specific screen
  15. Launch Gist Messenger on Clicking a Link
  16. Open a New Conversation on Clicking a Link
  17. Trigger a Custom Bot Conversation on Clicking a Link
  18. Open a Help Article within Messenger
  19. Gist JavaScript Events
  20. Troubleshooting

Identifying Leads and Users with Gist JavaScript API

The gist.identify() method pushes contact data into Gist. If the contact is not yet in your workspace, we will create a new record for them; otherwise, we update their record with the information you pass in.

Here are the different types of Gist JavaScript API that you can use to identify your leads and logged-in users or connect Gist to other apps.

1. Track Logged-In Users And Their Properties

When you want to track logged in uses; for instance, membership site or your SaaS app, and you want to send those users and their data to Gist, use the following code.

gist.identify("12345", { 
    "email": "johndoe@tacos.com", 
    "name": "John Doe",
    "subdomain": "app", // Put quotes around text strings
    "active_accounts": 1872, // Send numbers without quotes
    "last_paid_at" : 1283495946, // Send dates in unix timestamp format and end key names with "_at"
    "teammates": null, // Send null when no value exists for a user
    "tags": "Free, popular", // Multiple tags can be added separated by comma
    "overwrite_tags": false // Defaults to false. If set to false, will merge the tags
});

The default contact properties are treated as special properties. All other data passed in will be added to the contact's custom properties. Keys should be lowercase, with words separated by underscores.

Also, note that for this code to work, user id and email are mandatory attributes. You can also add any number of optional attributes to pass on to Gist.

This is the only method you can use to identify logged in users/customers on Gist. Here's a more detailed guide on how to identify your users/customers.

If you want to identify leads or subscribers who are not registered for membership on your site or app, then you can use the following:

2. Track Leads Without Custom Properties

If you're sending only the email address and do not want to collect other properties, then the syntax is:

gist.identify("email_address");

3. Track Leads With Custom Properties - Version 1

If you wish to send other custom attributes along with the email address, then the syntax is:

gist.identify({
    email: "email_address",
    name: "name",
    restaurant_type: "fine_dining"
});

4. Track Leads With Custom Properties - Version 2

This is another variation of the syntax above. If you are already using JavaScript code for identifying logged in users, as mentioned in 1., then you can use the same syntax, along with an empty string for user ID.

gist.identify("", {
    email: "email_address",
    name: "name",
    restaurant_type: "fine_dining"
});

Track Custom Events

The gist.track() method is appropriate when you simply wish to record a particular action that the contact has taken. Tracked events can show up in contacts' timelines.

The first argument is the name of the action to be recorded. The final parameter is a map that can be used to send optional metadata about the event.

gist.track("Registered", {
  plan: "Pro Annual",
  accountType: "Facebook"
});

Here's a separate detailed guide to learn how you can send custom events to your Gist workspace.

Track Pageviews in Single Page Apps

The Gist tracking code automatically tracks all pageviews and event for you so you won't have to. Having said that, if you wish to forcefully track a pageview, this method is appropriate for that.

gist.trackPageView();

This is particularly useful on a Single Page Application where a URL change doesn’t necessarily cause a page refresh; in this case you might want to manually call this method to initiate a page view call. In general, you can do that by simply calling:

window.onhashchange = function () {
  gist.trackPageView();
}

The actual implementation, however, would depend on the client-side framework you use, particularly its Router component.


Gist JavaScript API for Chat Messenger

Following is the JavaScript API you can call to show, hide, or load the Gist chat messenger on specific pages and to specific users.

Check If Gist Chat API Is Ready

The gistChatReady event indicates that Gist Messenger widget is loaded and the gist.chat() API is ready for use.

// This callback gets executed once Gist Messenger is fully loaded and all gist.chat() API methods are available
document.addEventListener('gistChatReady', function () {
    // your code goes here
    console.log('The gist.chat() api is ready now');
});

This event will only be processed once, when the JavaScript API is loaded.

It is highly recommended that you wrap any usage of the gist.chat() method around the gistChatReady event listener.

Changing the Width of Messenger

You can customize the width of the widget by including custom styles on your website. For example, in order to configure the height or width manually, you can use the following code:

@media only screen and (min-width: 768px) {
    .gist-messenger-iframe {
        width: 420px!important; // default is 380px;
    }
}

Alternatively, you can use Javascript to customize the widget position, height and width:

// Change the BOTTOM_SPACING and WIDTH values
var BOTTOM_SPACING = 110; // offset from the bottom
var WIDTH = 400;

// DO NOT TOUCH THE CODE BELOW
var widget = document.getElementsByClassName("gist-messenger-iframe")[0];
widget.style.bottom = BOTTOM_SPACING + "px";
var heightOffset = BOTTOM_SPACING + 20;
widget.style.height = "calc(100% - " + heightOffset + "px)";
widget.style.width = WIDTH + "px";

Hide the Messenger Widget

This call will hide the Gist chat messenger if it is loaded on that particular page. It will not hide the Messenger Launcher everywhere in general, but just hides on those pages where this script loads. To make this happen, you can call the following API method.

document.addEventListener('gistReady', function () {
    gist.chat('hide');
});

Make sure the gist.chat('hide') method is enclosed in a 'gistReady' event listener and not 'gistChatReady' event.

This is useful if you want to hide the chat messenger by default on a page and only display it when an event is triggered by your users, such as clicking a link or a button.

Show the Messenger Widget

This will display the Gist chat messenger on the page on which this API is called. To make this happen, you can call the following API.

gist.chat('show');

You can use this API call to show the Messenger only on specific pages of your website, such as your 'app' or member login area.

Open the Messenger Widget

This will open the Messenger Widget to the last page the user was on, if it is currently closed.

gist.chat("open");

Close the Messenger Widget

This will close the Messenger Widget, if it is currently opened.

gist.chat("close");

Show the Messenger Launcher

This will show the Messenger Launcher if it is hidden. It will not affect the main Messenger panel.

gist.chat("showLauncher");

Hide the Messenger Launcher

This will hide the Messenger Launcher if it is visible. It will not affect the main Messenger panel.

gist.chat("hideLauncher");

Change the layout of the Messenger

Change the main Messenger widget to the sidebar mode.

gist.chat("sidebar");

Change the main Messenger widget to the standard mode.

gist.chat("standard");

Clear session cookies for logged-out users

If you are using the identify method to track your logged-in users, then you should call the Gist shutdown method to clear your users' conversations and identity anytime they logout of your application. This ensures the next person using the computer doesn't see any previous history.

In order to do this, just use gist.chat('shutdown') to completely clear Gist's tracking cookies. To Gist, this is a brand new person now.

gist.chat('shutdown');

Alternatively, you can also clear cookies for those visitors who do not grant you the consent to store cookies.

/*
Example code to remove the cookies when a visitor clicks an element with the 'removeCookies' id.
*/
document.getElementById("removeCookies").onclick = function() {
    gist.chat('shutdown');
};

Callback When Unread Messages Count Changes

This event is triggered when a new incoming message arrives and the unread messages count changes for the visitor. You can use this to register a function that will be called immediately whenever the current number of unread messages changes.

document.addEventListener("onGistUnreadCountChange", function(e) {
  console.log(window.gistUnreadCount); // prints out the unread message count
});

Code Example: customize Messenger widget using JS API

The following snippet uses the hide() and show() methods to hide the Messenger widget from visitors until they receive a message.

// hide the widget when it first loads
document.addEventListener('gistChatReady', function () {
  gist.chat('hideLauncher');
});

// open the Messenger widget when you receive a message
document.addEventListener("onGistUnreadCountChange", function(e) {
  if(window.gistUnreadCount > 0)
    gist.chat('open');
});

If you are using a custom launcher, we recommend that you use the window.gistUnreadCount to update your custom unread counter/badge.


You can programmatically switch to specific screens within the Messenger using the available routes.

Open the Messenger to the Welcome screen

gist.chat("navigate", 'home'); // Welcome screen

Open the Messenger to the Previous Conversations screen

gist.chat("navigate", 'conversations'); // Previous Conversations screen

Open the Messenger to the new conversation page

gist.chat("navigate", 'newConversation'); // Message screen

Open the Messenger to the new conversation page with pre-filled text in the response text box

gist.chat("navigate", 'newConversation',"insert text"); // Message screen

Open the Messenger to the Search page

gist.chat("navigate", 'articles'); // Search screen

Open the Messenger to the Search page with pre-filled query in the search box

gist.chat("navigate", 'articles?q=insert-test-here'); // Search screen

You can launch the Gist Messenger without the Gist launcher using the following API method:

gist.chat('show'); // call if Messenger widget is hidden
gist.chat('open'); // open the Messenger widget

For example, you can add a link anywhere on your site, including HTML text or buttons on a particular page and turn it into your own custom Gist Messenger launcher.

If you are using jQuery library, here are code sample that demonstrates how you can apply this method:

document.addEventListener('gistChatReady', function () {
    gist.chat('open');
});

Note: make sure you call the above-mentioned methods only with the gistChatReady event listener.

You can set up Gist to launch the chat messenger when your users perform a specific event on your website, such as clicking a link or a 'Contact Us' button. To make this happen, you can call the following API.

gist.chat("navigate", 'newConversation');

This function can also take an optional second parameter, used to pre-populate the message composer as shown in the code example below.

gist.chat("navigate", "newConversation","insert pre-populated text");

For example, you can add a link anywhere on your site, including HTML text or buttons on a particular page, which when clicked will load the Gist chat messenger ready for a new conversation. This can be used to enable chat to only those users that perform those actions and avoid everyone else.

If you have any questions about our pricing, please <a href="#" onclick="gist.chat("navigate", 'newConversation', 'Question about pricing: ')">contact our support team</a>

Example use case:

If you do not wish to display the chat messenger by default, but only launch it when a user clicks on a link or button on that page, you can use a combination of the gist.chat('hide'); and gist.chat("navigate", "newConversation"); calls to achieve this.

You can trigger a custom bot conversation when your visitors click a link using #GistLink. When you create a bot, make sure you give it a GistLink so you can use it to trigger the bot:

var GIST_BUTTON_SELECTOR = 'gist-open-bot'; // Replace this with the ID of the button that triggers the bot.
var GIST_LINK = "#testbot123"; // Replace testbot123 text with your bot's Gist Link.
window.onload= function () {
  document.addEventListener('gistChatReady', function () {
    const button = document.getElementById(GIST_BUTTON_SELECTOR);
    button.addEventListener('click', function(e) {
      var url_obj = new URL(window.location.href);
      url_obj.hash = GIST_LINK; 
      window.location.replace(url_obj.href);
      e.preventDefault();
    });
  });
}

And make sure the button or link that you want to trigger bot has the "gist-open-bot" ID.

<button type="button" id="gist-open-bot">Click Me!</button>

Open a Help Article within Messenger

There are many ways to open a Help Article within Messenger via any element on your site, and you can choose to do it using a custom HTML data attribute, or with the Gist JavaScript API.

All you’ll need is the Article’s ID, which can be found in the URL of the article you want to open. The editor URL is structured like this:

https://yourkbdomain.com/article/[ARTICLE ID]-article-slug

Using Custom HTML

Data attributes are the simplest way to open a Help Article via any link or button on your site. There are two different attributes you can choose from, which can be used to open the article in Messenger, or in a sidebar. Check out the examples and demos below for more information on how to use them.

Example

<!-- Open Article in Messenger-->
<a href="javascript:void(0)" data-gist-article="ARTICLE_ID"></a>

<!-- Open Article in a sidebar -->
<a href="javascript:void(0)" data-gist-article-sidebar="ARTICLE_ID"></a>

Using JS API

Alternatively, you can use the gist.chat('article') method to open the Article within Messenger, or in a sidebar. This is helpful when your trigger is something other than a link or a button, or when you’d like the article to show up automatically using your own custom logic.

Note: If the Messenger is closed when this method is called, it will also open the Messenger automatically.

Example

// Open Article in Messenger
gist.chat('article', 'ARTICLE_ID')

// Open Article in a sidebar
gist.chat('article', 'ARTICLE_ID', 'sidebar')

If you are not familiar with Javascript code, don't fret. Here's a quick HTML code that you can copy into your page to open any article you need.

<a href="javascript:void(0)" onclick="gist.chat('article', 'ARTICLE_ID')"></a>

Replace ARTICLE_ID with the ID of the article from the URL structure.


Gist JavaScript Event

You can use our JS API to send Gist events to an outside platform or trigger custom JavaScript to build plugins of your own.

Initialize your Gist Messenger

The ready event indicates that Gist Messenger is ready for use.

document.addEventListener("gistChatReady", function(e) {
  // your code goes here
})

Messenger Events

If you want to listen for the Messenger window opening or closing to perform any event or visual updates on your site, you can use the messenger:opened and messenger:closed events.

Messenger opened

// Triggers when the Messenger has been opened
document.addEventListener('messenger:opened', function (data) {
  // your code goes here
}, false);

Messenger closed

// Triggers when the Messenger has been closed
document.addEventListener('messenger:closed', function (data) {
  // your code goes here
}, false);

Conversation Events

Conversation started

The conversation:started event fires when the user starts a new chat conversation in the Messenger.

// Triggers when a new conversation has started
document.addEventListener('conversation:started', function (data) {
  // your code goes here
}, false);

Conversation opened

The conversation:opened event is triggered when the user selects a conversation from their history in the Messenger.

// Triggers when a conversation has been opened
document.addEventListener('conversation:opened', function (data) {
  // your code goes here
}, false);

Both these conversation events pass the conversationId as payload.

Conversation feedback

The converastion:feedback event is triggered when the user submits their feedback on a conversation they had with your team.

// Triggers when a satisfaction rating has been left
document.addEventListener('conversation:feedback', function (data) {
  // your code goes here
}, false);

This event passes the conversationId and rating object as payload.

Message Events

Message sent

The message:sent event fires when the user replies to a conversation.

// Triggers when a message has been sent
document.addEventListener('message:sent', function (data) {
  // your code goes here
}, false);

Message received

The message:received event fires when the user receives a reply to a conversation from a teammate.

// Triggers when a message has been received
document.addEventListener('message:received', function (data) {
  // your code goes here
}, false);

Both these conversation events pass the conversationId and message as payload.

Email Captured

The email:captured event fires when the user enters their email address in the Messenger.

// Triggers when an email address has been captured
document.addEventListener('email:captured', function (data) {
  // your code goes here
}, false);

This event passes the email the user submitted as a payload.

GDPR consent

The gdpr:clicked event fires when the user clicks on the yes or no consent buttons as part of the form prior to starting a conversation.

// Triggers when the GDPR form has been submitted
document.addEventListener('gdpr:clicked', function (data) {
  // your code goes here
}, false);

This event passes the email, accepted and visitorId as a payload.

Meeting Events

Meeting requested

The meeting: requested event fires when a meeting request has been pushed to a conversation when a bot flow triggers it or when a member of your team shares a calendar to a conversation.

// Triggers when a meeting has been requested
document.addEventListener('meeting:requested', function (data) {
  // your code goes here
}, false);

This event passes the conversationId as payload.

Meeting booked

The meeting:booked event fires when the user books a meeting with a member of your team.

// Triggers when a meeting has been scheduled
document.addEventListener('meeting:booked', function (data) {
  // your code goes here
}, false);

This event passes the meeting object as payload.

In-App Message Events

The triggeredMessage:fired event is triggered when the in-app message is show to your visitor.

// Triggers when an in-app chat message has been sent
document.addEventListener('triggeredMessage:fired', function (data) {
  // your code goes here
}, false);

The triggeredMessage:clicked event is triggered when the user interacts with an in-app message by clicking on the message.

// Triggers when an in-app chat message has been clicked
document.addEventListener('triggeredMessage:clicked', function (data) {
  // your code goes here
}, false);

The triggeredMessage:dismissed event is triggered when the in-app message is closed by your visitor by clicking on the close button next to the message.

// Triggers when an in-app chat message has been dismissed
document.addEventListener('triggeredMessage:dismissed', function (data) {
  // your code goes here
}, false);

These in-app message events pass the conversationId, message and assistantId as payload.

Chatbot Events

Chatbot fired

The chatbot:fired event is triggered when the welcome message of the chat bot is show to your visitor.

// Triggers when a chat bot has been triggered
document.addEventListener('chatbot:fired', function (data) {
  // your code goes here
}, false);

Chatbot button clicked

The chatbot:buttonClicked event fires when the user clicks on a button in chat as a response to a bot question.

// Triggers when a button response in a chatbot has been clicked
document.addEventListener('chatbot:buttonClicked', function (data) {
  // your code goes here
}, false);

These bot events pass the conversationId, buttonText, buttonId, questionId and createdAt as payload.

Article Events

Article viewed

The article:viewed event is triggered when a user views an article within the Messenger.

// Triggers when an article has been viewed
document.addEventListener('article:viewed', function (data) {
  // your code goes here
}, false);

This event passes articleId, articleTitle, articleUrl and authorId as payload.

Article searched

The article:searched event is triggered when a user searches for an article in the Messenger.

// Triggers when an article has been searched
document.addEventListener('article:searched', function (data) {
  // your code goes here
}, false);

This event passes searchTerm and resultsCount as payload.

Article feedback

The article:feedback event is triggered when a visitor leaves a feedback on any article.

// Triggers when feedback has been left for an article
document.addEventListener('article:feedback', function (data) {
  // your code goes here
}, false);

This event passes articleId and rating object as payload.

An example script

This example shows listening to a variety of Gist client side events and logging their contents whenever they happen.

Link: https://gist.github.com/jittarao/9b2ef36418fb8ef4b6d353ba2419f2d6


Troubleshooting

Any Gist JS API method may be executed manually. Use the Network tab to inspect requests.

How do I open the Javascript console in your debugger?

The Javascript console reveals all requests, outbound and inbound, to your browser. Additionally, you may execute valid Javascript.

Chrome: COMMAND+OPTION+J (Mac) or CTRL+SHIFT+J (Windows).

Firefox: COMMAND+OPTION+K (Mac) or CTRL+SHIFT+K (Windows) and then click on the Console tab.

Safari: COMMAND+OPTION+I (Mac) or CTRL+ALT+I (Windows) and then click on the Console tab.

IE: F12 and then click on the Console tab.

Are you loading Gist Tracking Code?

Open the Javascript console and enter gist. Does it return an object, as seen below?

The object means that you are successfully loading Gist tracking code onto your website. If you get an undefined error, the tracking code hass not loading successfully:

Are you loading two instances of Gist tracking code?

Please note that you cannot load the tracking code twice on the same page, even if you’re using different workspace IDs. You might encounter Uncaught RangeError: Maximum call stack size exceeded. You can conditionally set the Workspace ID based on an environment variable.

Example:

var workspaceId;
ENV === 'production' ? workspaceId = 'A' : workspaceId = 'B';

Do you have any ad blockers enabled in your browser?

Gist uses cookies/local storage to store information about users in the browser. Ad blockers prevent cookies and other data we rely on to make valid requests to the tracking servers. Some portion of your users are probably using ad blockers, which prevent the Gist tracking code from fully executing. Both desktop and mobile browsers are impacted.

Is your web site deployed under a domain on the Public Suffix List?

The Public Suffix List is a catalog of certain Internet effective top-level domains–enumerating all domain suffixes controlled by registrars.

The implications of these domain suffixes is that first party cookies cannot be set on them. Meaning, foo.example.co.uk can share cookie access with bar.example.co.uk, but example.co.uk should be walled off from cookies at example2.co.uk. The latter two domains could be registered by different owners.

Examples of domains on the Public Suffix List that are common in troubleshooting include:

*.github.io

*.herokuapp.com

*.appspot.com


Need Help?

If you have any questions, please start a Live Chat. Just "Click" on the Chat Icon in the lower right corner to talk with our support team.

Did this answer your question?