JavaScript API

Installing HelpCrunch Live Chat 2.0 on your web enables you to communicate with your web app visitors and registered users. To get going, follow these step-by-step instructions.

Integration

    1. Create a new web app

      To add a new app, log in to your HelpCrunch account, then go to the Settings pageSet up & CustomizeWebsite Widgets and press “Add new”. Fill the Widget Name field and press “Apply” button.

    2. Get HelpCrunch widget’s JS code

      For the next step, you’ll need the widget’s JavaScript code. You can copy this code on apps list in your HelpCrunch account (Settings pageSet up & CustomizeWebsite WidgetsYour app nameSetup)

      Website Widget JS Code

  1. Add widget’s JS code to your site

    Paste this JS code before the closing body tag to of every page of your website where you want HelpCrunch live chat to appear. JS code consists of initialization and showChatWidget methods.

Displaying the chat widget on your site

Deciding when to display HelpCrunch Live Chat

By default, HelpCrunch chat widget appears on your page after initialization because of showChatWidget method in your widget’s JS code:

HelpCrunch('showChatWidget');
You can change that by cutting out that part of the code and displaying the widget right after your custom event (like a button click).

Also you can hide the widget by calling hideChatWidget method

HelpCrunch('hideChatWidget');

Force open/close chat after custom event

If you want to open or hide HelpCrunch chat by some custom event on your page – just call openChat / closeChat methods when your event fires:

HelpCrunch('openChat');
HelpCrunch('closeChat');

How to create a custom chat widget

There is a chat widget available by default. However, you can create your own widget that fits better with your design.

Copy API code in accordance with step 1.

Exclude showChatWidget call from from copied API code

HelpCrunch('showChatWidget');

Once SDK is loaded, use onReady event to show your custom widget


HelpCrunch('onReady', function() {
  // Show your widget
});

To open the chat use the openChat

HelpCrunch('openChat');

If you need to change your widget view depending on your chat is open or closed, use onChatOpen and onChatClose events

HelpCrunch('onChatOpen', function() {});
HelpCrunch('onChatClose', function() {});

To display a number of unread messages use onNewUnreadMessages event


HelpCrunch('onNewUnreadMessages', function(event) {
  // event.unreadMessages
});

Example: open chat by clicking on a button or link

If you don’t want to display the widget on all your website/product pages by default, but you still want to open the chat if a visitor/user clicks on a “Contact Us” button – do the following:

  1. Remove HelpCrunch('showChatWidget'); from your HelpCrunch chat widget JS code: This will make the chat hidden by default.
  2. To show the chat on the button/link click, add this JS code to your website:
    
    HelpCrunch('onReady', function() {
      document.getElementById('contact-us').onclick = function() {
        HelpCrunch('openChat');
      }
    });
    
  3. That’s it. Now go to your website and check how it works.

Example: Hide chat until the first message from agent or first proactive chat message

If you don’t want to display the widget on all your website/product pages by default, but you still want to open the chat if a visitor/user clicks on a “Contact Us” button – do the following:

  1. Remove HelpCrunch('showChatWidget'); from your HelpCrunch chat widget JS code: This will make the chat hidden by default.
  2. To show the chat only after the first chat message, add this JS code to your website:
    
    HelpCrunch('onNewUnreadMessages', function() {
      HelpCrunch('showChatWidget');
    });
    
  3. That’s it. Now go to your website and check how it works.

User authentication mode

User authentication mode provides a seamless experience for a business and for a customer across different devices. It offers continuity across web, iOS and Android platforms and lets you keep all interaction with a given customer in the same chat thread no matter what device he/she is logged in from. User authentication mode helps make sure that one user can’t impersonate another and therefore we strongly recommend all our clients to enable this mode.

Common usage

The most common usage of the User authentication mode is to integrate it with your registration/login system. You can install HelpCrunch chat widget on your landing page to talk to your visitors, for example, and inside your service (in-app messenger) to support your registered users. Once your visitor registers/logs in with your service and gets a User ID in your database, you can enable the User authentication mode for that user.

How it works

In order to enable User authentication mode, you should modify HelpCrunch Initialization code. We initiate the user authentication mode once you specify a user_id parameter inside user object during the initialization process. Example:


HelpCrunch('init', '<your organization domain>', {
  applicationId: <application id>,
  applicationSecret: '<application secret>',
  user: {
    email: '<user email>',
    name: '<user name>',
    phone: '<phone number>',
    user_id: '<user_id>',
  }
});

Important note: user_id attribute must be unique (usually our clients use a User ID from their user database).When you send us the user_id, e.g. 12345, we automatically authenticate this user and load all previous corresponding chat history and user personal/behavioral data (aka user profile) to your agent chat and chat history to user’s chat. So, if a user logs in to your service/product/app from his home desktop first, talks to you via chat, then logs in from his work laptop – the chat history and all the related user data will be always available for you and your customer.

Important note: it is highly recommended to specify user_id together with the user name and user email. Otherwise the email address field in the user profile will be empty, and user name will be randomly generated by us, e.g. Giant Duck (anonym) or Colored Leopard (anonym).

Important note: if the user authentication mode is enabled, the pre-chat form will not be displayed before the chat start. If you send us just the user name and/or user email without indicating the user_id – the user authentication mode will not be enabled but the name and/or email fields of the pre-chat form will be pre-filled and the form will be displayed before the chat start (when the form is enabled in the setings of your account).

Authenticated users

These are all users available in HelpCrunch Users section. If you enable User authentication mode, all registered/logged in users will automatically fall into Contacts section even if they’ve had no chats with you previously. You can also import users from a CSV file thus making them authenticated. Plus any user, who had a chat with you (at least one successfully sent message from the user who filled in his data in the pre-chat form) is considered an authenticated user.

Security

If you want to be sure that no one substitute the user ID to view another person’s chat history and chat under his name you have two options:

    1. Fast / easy one: hash your user ID with some hash salt and put this hash to user_id field instead of a real ID (it’s okay to pass the string to this field)

 

    1. Send a security_hash parameter right with user_id. It is optional and can be any string (like password hash, for example). After you have sent a security_hash once – you will need to send it every time for current user_id or you’ll get 403 and a clean chat.

 

 

 

Custom Data

HelpCrunch widget allows to collect your users’ data and use it inside your HelpCrunch account. You can pass the user’s data during the widget initialization (as we did at user authentication mode section of this page) or you can send it manualy:

Update main user attributes

You can update main attributes of your customer at any time by calling an updateUser method:


var user = {
  email: '<user email / email>',
  name: '<user name / string>',
  user_id: '<user id / string>',
  phone: '<phone number / string>'
};
HelpCrunch('updateUser', user);

After you have added user’s data and called HelpCrunch('updateUser', user); , this data will appear at your HelpCrunch admin account in chat with that user:

Sent User data in chat

Add custom attributes to meet specific business criteria

In addition to the user’s name / email / ID, HelpCrunch lets you send additional attributes of your customers in custom data. You can do by calling updateUserData method: HelpCrunch('updateUserData', userData); . In userData you can send any information about users you wish to track as object of key/value pairs, that can contain numbers, strings or boolean data. This feature will only work if your user has a user_id attribute:


var userData = {
  money_spent: 2500,
  subscription: 'gold',
  accepted_agreement: true,
};
HelpCrunch('updateUserData', userData);

You can combine sending main attributes and custom data in one updateUser call:


var user = {
  email: '<user email / email>',
  name: '<user name / string>',
  user_id: '<user id / string>',
  phone: '<phone number / string>',
  custom_data: {
    money_spent: 2500,
    subscription: 'gold',
    accepted_agreement: true,
  },
};
HelpCrunch('updateUser', user);
You can also combine it right at the chat initialization method to make even less server calls:

var helpCrunchOptions = {
  applicationId: <application id>,
  applicationSecret: '<application secret>',
};
if (someAuthCheckMethodOfYourWebsite()) {
  helpCrunchOptions.user = {
    email: '<user email / email>',
    name: '<user name / string>',
    phone: '<phone number / string>',
    user_id: '<user_id / string>',
    custom_data: {
      money_spent: 2500,
      subscription: 'gold',
      accepted_agreement: true,
    },
  };
}
HelpCrunch('init', '<your organization domain>', helpCrunchOptions);

Custom data parameters will appear in chat with user at your HelpCrunch admin account just as same as main user attributes (name, email, user id):

Custom data in chat

Also you will be able to search or filter your users by custom data at the “Contacts” page. There 3 types of custom data you can search by: integers, strings and boolean:

Custom data search

 

Track custom events

You can send HelpCrunch any customer activities performed by users in your web or mobile app. For example, you could track how users navigate in your web or mobile app, what pages users visit, what goods users have added to their shopping cart, what goods users have purchased in your app, etc. You can submit an event using the trackEvent method. This will associate the event with the currently logged in user and send it to HelpCrunch.
HelpCrunch('trackEvent', eventName);
Once you’re sending HelpCrunch this data, events will be tracked and shown in customer profile in order as it happens: Custom Events in chat By default, HelpCrunch widget tracks user navigation by “Page View” events.

 

 

Integrate Google Analytics tracking

If you want to track HelpCrunch chat/widget events in your Google Analytics account, you can easily add tracking codes to your web page with HelpCrunch widget. For example, if your Google Analytics function is “ga” (default one) you will need to add these codes after HelpCrunch(‘init’): Track when your customer sends a message in chat with onCustomerMessage event:


HelpCrunch('onCustomerMessage', function (event) {
  ga('send', 'event', 'customer', 'sendChatMessage');
});

Track when your customer opens the chat:


HelpCrunch('onChatOpen', function () {
  ga('send', 'event', 'customer', 'opensChat');
});

Track when your customer closes the chat:


HelpCrunch('onChatClose', function () {
  ga('send', 'event', 'customer', 'opensChat');
});

Track when your customer receives a new message with onNewUnreadMessages event:


HelpCrunch('onNewUnreadMessages', function () {
  ga('send', 'event', 'customer', 'getsNewMessage');
});

If you want to track any other event in Google Analytics – please contact us in chat from your HelpCrunch admin account and we will arrange it for you.

Localization

The following steps describe the localization process by using phrase lists. Also you can use just for customizing chat texts.

Step 1. Adding localizations and phrase lists

First of all you need to create your Phrase Lists. Go to your HelpCrunch account, then open Settings / Website Widgets, find your Website Widget, click on it and open Localization tab there. Add a separate Phrase List for each language that you want to support. Then edit each phrase list texts to match the language.
You’ll have English, Spanish, Italian, Portuguese, Polish, German and Russian languages (already translated) by default upon your registration:

Localization

Important note: If you want to enable automatic detection of localization depending on user’s browser language, you should use the two-letter language code as the Phrase List Name.
Examples: en, fr, de, pt, es. (see full list of ISO 639-1 codes)

Step 2. Enabling localizations

In order to enable any exact Phrase List by it’s name you should add the following command (call to a setPhraseList method) to the chat widget js code:

HelpCrunch('setPhraseList', 'en');

If you named all your Phrase Lists with the two-letter language codes, you can add the following command to the chat widget js code in order to automatically detect the user’s browser language and enable the corresponding Phrase List:

HelpCrunch('setPhraseList', navigator.language.slice(0,2));

Right-to-Left text language support

Adding support for HelpCrunch to be localized into a right-to-left (RTL) language, such as Hebrew, is simple. You can also do that on a per page basis, for example if you have both English and Hebrew on your site, you can paste the following code onto RTL pages beneath your existing HelpCrunch code:


HelpCrunch('setRtlDirection')

Send proactive chat auto-messages with JavaScript API

Sometimes you need to send a proactive chat auto-message after a user does some custom action on your website or when proactive chat rules are just not enough to meet some complex conditions. In these cases, you can trigger a proactive chat auto-message with JavaScript by calling sendProactiveChatAutoMessage method.

All you need to know is your proactive chat auto-message ID. You can view it after you have created the auto-message at the header of its editing page (like “Edit Auto Message (ID 1420)”):

Auto Message ID

For example, if auto-message ID is 1420, you can fire it by code:

HelpCrunch('sendProactiveChatAutoMessage', 1420);

If you want to create a proactive chat auto-message that will be triggered only by JavaScript API call, you should choose radio button “Launch only with widget API” in “Proactive chat rules” section at the bottom of the auto-message create/edit page:

Proactive Chat Rules

 

Methods

HelpCrunch widget provides you with small JavaScript API on your website. With it you can control and customize your chat and widget behavior.

showChatWidget

Shows the chat widget (chat start button) after the initialization or after it was hidden by hideChatWidget.

No parameters or returns.


HelpCrunch('showChatWidget');

hideChatWidget

Hides the chat widget (chat start button) after it was displayed by showChatWidget.

No parameters or returns.


HelpCrunch('showChatWidget');

openChat

Opens the HelpCrunch chat. Can be called without displaying the widget.

No parameters or returns.


HelpCrunch('openChat');

closeChat

Closes the HelpCrunch chat after it was opened by openChat.

No parameters or returns.


HelpCrunch('closeChat');

init

Initializes the HelpCrunch widget on your website page. All web SDK methods that was called before this method will run after it will finish the initialization.

You can take this method with all required parameters right from your HelpCrunch account at Settings pageSet up & CustomizeWebsite WidgetsYour app nameSetup

Parameters:

  • organization domain: string, domain of your organization, that you have entered during the registration, you can check it in url of your admin account, like DOMAIN.helpcrunch.com
  • options: object
    • applicationId: string
    • applicationSecret: string
    • user (optional): object – if the user is authenticated at your website, you can send the user’s data right during the initialization to authenticate the user in HelpCrunch chat automatically and make fewer server requests later. Read more about it in user authentication mode section, view detailed user format in web SDK user section
    • signature (optional): string – needed only in user authentication mode when you want protect your user data with backend security signature. Read more about it in security signature section

Default initialization:


HelpCrunch('init', '<your organization domain / string>', {
  applicationId: ,
  applicationSecret: '<application secret / string>',
});

Initialization with all user/lead data:


HelpCrunch('init', '<your organization domain / string>', {
  applicationId: ,
  applicationSecret: '<application secret / string>',
  user: {
    email: '<user email / email>',
    name: '<user name / string>',
    phone: '<phone number / string>',
    user_id: '<user_id /string>',
    security_hash: '<security_hash /string>',
      custom_data: {
      money_spent: 2500,
      subscription: 'gold',
      accepted_agreement: true,
    },
  },
  signature: 'e8aa8af95cd6a05b80308dcb3dd6901d',
});

updateUser

Use it to add or update current customer parameters, such as name, email, phone, company and customData (an object with any random data you want to write). If there is no user initialized for the current visitor, this method will create a new user and you will be able to see it at the Contacts page in your HelpCrunch account. This method is useful when the user makes any changes in his main attributes you want to write and you want to see it in your HelpCrunch account instantly. Parameters:

 

 

 


var user = {
  email: '<user email / email>',
  name: '<user name / string>',
  user_id: '<user id / string>',
  phone: '<phone number / string>',
  security_hash: '<security_hash /string>',
  custom_data: {
    money_spent: 2500,
    subscription: 'gold',
    accepted_agreement: true,
  },
};
HelpCrunch('updateUser', user, 'e8aa8af95cd6a05b80308dcb3dd6901d');
Example:
In your single page application user changes (or adds) his email. To see this change in HelpCrunch admin panel, you can just call

var userEmail = 'email@somedomain.com';
HelpCrunch('updateUser', { email: userEmail });

updateUserData

Updates current user’s custom data. Custom data is an object with any random data you want to write and then use in your HelpCrunch account. Read more about it in web SDK custom data section. This method is useful when the user makes any changes in his custom attributes and you want to see it in your HelpCrunch account instantly. Parameters:

 

 


var userData = {
  money_spent: 2500,
  subscription: 'gold',
  accepted_agreement: true,
};
HelpCrunch('updateUserData', userData);

Example:
You want to count how many times your user clicked some important button: you store counter in localStorage and onClick call


document.getElementById('important-button').onclick = function () {
  var counter = window.localStorage.getItem('counter');
  counter++;
  window.localStorage.setItem('counter', counter);
  HelpCrunch('updateUserData', { importantButtonClicks: counter });
}

trackEvent

You can track any custom events the user does in your website and view his event history in HelpCrunch account. Read more about it in the track custom events section.

Parameters:

  • eventName: string


HelpCrunch('trackEvent', eventName);

Example:
You want to know that user has clicked the “checkout” button. The code will look like this:


document.getElementById('checkout-button').onclick = function() {
  HelpCrunch('trackEvent', 'checkoutButtonClick');
}

setPhraseList

Call setPhraseList if you want to launch a custom localization or custom chat texts. By default there are 6 languages available and the chat will pick the localization corresponding to the browser language. If that language is not found, chat will display the default one. Read more about it in the localization section.

Parameters:

  • phraseListName: string


HelpCrunch('setPhraseList', phraseListName);

Example:
You have created a Klingon language phrase-list in you admin account and called it “klingonian”. To enable it in the HelpCrunch chat on your page, run this code before showing the chat widget:

HelpCrunch('setPhraseList', 'klingonian');

sendProactiveChatAutoMessage

HelpCrunch has a proactive chat auto-message system to automatically address visitors and leads. You can configure the auto-message rules in your HelpCrunch account or just call it from web SDK JS API. Read more about it in the send proactive chat auto-messages with JavaScript API section.

Parameters:

  • autoMessageId: number


HelpCrunch('sendProactiveChatAutoMessage', autoMessageId);

Example:
You want to offer a discount to your customer if he sorts your goods by price in ascending order or just clicks “Get a discount!” button (or whatever you want). For this, you need to create a proactive chat auto-message in your HelpCrunch account, enable it and get its ID from its editing page. Assuming that ID is (for example) 1420, the code can be:


var proposeDiscount = function () {
  HelpCrunch('sendProactiveChatAutoMessage', 1420);
}
document.getElementById('i-want-discount-button').onclick = proposeDiscount;
document.getElementsByClassName('sort-goods').onclick = function (event) {
  if (event.target.attributes.order == 'asc' && event.target.attributes.field == 'price') {
    proposeDiscount();
  }
}

sendUserMessage

Sometimes you need to send your support agent a message on behalf on your website user on some custom user action. This method is right for it.

Parameters:

  • messageText: string


HelpCrunch('sendUserMessage', messageText);

Example:
You want your support agent to receive a message with “CALLBACK: +12312312313” text when the user enters his phone number on some form and clicks a “Call me back” button on your website. This code will look like:


document.getElementById('callback-button').onclick = function () {
  var phoneNumber = document.getElementById('callback-input').value;
  if (phoneNumber) {
    HelpCrunch('sendUserMessage', 'CALLBACK: ' + phoneNumber);
  }
}

logout

On some websites user can have multiple accounts and can login/logout to switch between them. If you use user authentication mode you can do the same for your HelpCrunch widget, so the data from one user account will not pass to another. You can use logout method to do it:

No parameters or returns.


HelpCrunch('logout');

Events

When HelpCrunch widget is loaded – you can bind callbacks to HelpCrunch chat events. For example, it can be useful for adding analytics tracking.

onReady

This event fires when chat widget was initialized and your application data was loaded

No parameters are passed to the callback function

HelpCrunch('onReady', callback);

onChatOpen

This event fires when your customer opens the chat

No parameters are passed to the callback function

HelpCrunch('onChatOpen', callback);

onChatClose

This event fires when your customer closes the chat

No parameters are passed to callback function

HelpCrunch('onChatClose', callback(event));

onCustomerMessage

This event fires when your customer sends a message in chat

Parameters:

  • customerMessage: object
    • detail: object
      • message: object
        • author_name: string (user name)
        • cid: string (user id)
        • text: string
        • time: string
        • file: object


HelpCrunch('onCustomerMessage', callback(customerMessage));

Example:
You want to show the last customer’s message at the status block of your website:


HelpCrunch('onCustomerMessage', function (customerMessage) {
  var message = customerMessage.detail.message;
  document.getElementById('status-input').value = message.author_name + ': ' + message.text;
});

onNewUnreadMessages

This event fires when your customer receives a new message in chat:

Parameters:

  • event: object
    • unreadMessages: number


HelpCrunch('onNewUnreadMessages', callback(event));

Example:
You want to show a big red bubble with unread messages in your user’s status bar at your website:


  HelpCrunch('onNewUnreadMessages', function (event) {
  var bigRedBubble = document.getElementById('big-red-bubble');
  if (event.unreadMessages > 0) {
    bigRedBubble.style.display = 'inline';
    bigRedBubble.textContent = event.unreadMessages;
  } else {
    bigRedBubble.style.display = 'none';
  }
});

User entity format

This is how you can send data about your user/lead/customer to HelpCrunch during the initialization or by updateUser method.

Structure:

  • user: object
    • email: string – optional – must be a valid email, not unique
    • name: string – optional – any string, not unique
    • phone: string – optional – any string, not unique, no checks for number
    • user_id: string – optional – unique user ID, there are a lot of tricks here, please check the user authentication mode section to be sure you do everything right
    • security_hash: string – optional – works only with user_id – if you want to be sure, that no one steals you customer’s chat – you can pass this parameter (after you sent it once you will need to send it every time with that user_id). Please check the security note in the user authentication mode section
    • custom_data: object – optional – an object with random key/value pairs, where value can not be another object or array, be aware that all keys your pass there will appear as filters in your HelpCrunch account’s advanced search. Read more about it in the custom data section

Example:


var user: {
  email: 'some-email@example.com',
  name: 'Ivan Dobsky',
  phone: '+43211234090',
  user_id: '1984',
  security_hash: 'ec02c59dee6faaca3189bace969c22d3',
  custom_data: {
    money_spent: 2500,
    subscription: 'gold',
    accepted_agreement: true,
  },
};

Security signature

If you use our User Authentication Mode and you don’t want the pre-chat/offline forms to be displayed in your chat widget, you can still ensure that no one is able to send any random data through your widget. This can be done by generating a special secret and utilizing a security signature on your backend.

To create this signature you need to generate the secret in your HelpCrunch account (Settings pageSecurity):

When the secret is generated, you can create a signature on you backend with its help. To do that, you need to JSON encode a user data from your request, concatenate it with the secret, make an MD5 hash of it, and add this hash/signature to the init or updateUser method. Here is the PHP example:

$user = [
'email' => 'some@email.com',
'name' => 'The Name',
'user_id' => '12345',
'phone' => '+49123221312',
];
$signature = md5(json_encode($user) . 'your organization secret');
?>
HelpCrunch('init', 'your organization domain', {
applicationId: 'application id',
applicationSecret: 'application secret',
user = {
email: '<?= $user['email'] ?>',
name: '<?= $user['name'] ?>,
user_id: '<?= $user['user_id'] ?>',
phone: '<?= $user['phone'] ?>'
},
signature: <?= $signature ?>
});