NAV
Javascript Command queue

Overview

Installation code looks like this:

(function(w,d,v3){
w.chaportConfig = {
  appId : '<insertYourId>',
  // put your configuration options here
};

if(w.chaport)return;v3=w.chaport={};v3._q=[];v3._l={};v3.q=function(){v3._q.push(arguments)};v3.on=function(e,fn){if(!v3._l[e])v3._l[e]=[];v3._l[e].push(fn)};var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://app.chaport.com/javascripts/insert.js';var ss=d.getElementsByTagName('script')[0];ss.parentNode.insertBefore(s,ss)})(window, document);

Do you want to have more control over the chat widget or want to integrate Chaport closely with your user base? This documentation is what you need. It covers existing configuration options and available methods.

Configuration options should be added to your installation code the way it's shown on the right.

API methods can be called 1 of 2 ways.

Email: JS API Help

Configuration

You can pass any of the options below in your installation code.

appId

window.chaportConfig = {
  appId: '<yourAppId>',
};

Required, this option is included in the installation code, that you can retrieve at "Settings -> Installation code", and it shouldn't be modified.

analytics

Pass data directly to Analytics (useful if you have GTM installed):

window.chaportConfig = {
  appId: '<yourAppId>',
  analytics: {
    google: {
      id: 'G-...',
    },
  },
};

Use a renamed GTM dataLayer variable:

window.chaportConfig = {
  appId: '<yourAppId>',
  analytics: {
    google: {
      id: 'G-...',
      api: 'gtm', // required if you also pass apiObject
      apiObject: window.yourDataLayerVariable,
    },
  },
};

Optional. Widget automatically detects Google Analytics on your website even without this option. However, if you have multiple IDs or GA codes installed, you may want to specify which one the widget should use.

Note: Here and below, a capitalized GA refers to any version of Analytics installed on your website using Google Tag, GTM or other methods.

Type: object

Property Type Notes
google object The config of your Google Analytics integration
google.id string Specify Google Tag ID if your installed GA's default ID isn't the one you need.
google.api string If you have multiple codes installed or use a customized apiObject (see below), you may have to specify what kind of GA code you use. Should be one of ['gtag', 'gtm', 'ga', 'gaq'], and by default detected and prioritized in that exact order.
google.apiObject any Pass GA api object here if you use it under a non-default name, making it impossible for the widget to detect it on its own.
google.enabled boolean Pass false if you don't want the widget to pass any events to your Analytics account.

appearance

window.chaportConfig = {
  appId: '<yourAppId>',
  appearance: {
    windowColor: '#a077bc',
    teamName: 'My test team',
    onlineWelcome: 'Hello, we are online!',
    offlineWelcome: 'We are not online.',
    position: ['left', 20, 20],
    textStatuses: true,
  },
};

Optional. Allows overriding your account-wide appearance settings on a per-page/per-site basis.

Type: object

Property Type Notes
windowColor string Hex color representation or one of ['dark-gray', 'gray', 'blue-gray', 'red', 'pink', 'purple', 'blue', 'light-blue', 'teal', 'green', 'orange' ]
teamName string Team name in the widget header
onlineWelcome string Online welcome in the widget header
offlineWelcome string Offline welcome in the widget header
position array Array with up to 3 elements. The first element is a string of either "left" or "right" (left bottom or right bottom position), second and third elements are optional X- and Y-offsets from the closest corner.
textStatuses boolean Whether the widget should display Unread/Read/Sending in the form of text or checkmarks.

assignments

window.chaportConfig = {
  appId: '<yourAppId>',
  assignments: {
    rules: [
      // assign to the example.com team if a visitor is on example.com
      { 'example.com-team-id': ['page_url', 'contains', 'example.com'] },
    ],
  },
};

Optional. Allows overriding your account-wide assignment rules. You'll need to use operator and/or team IDs for your assignment rules.

Type: object

Property Type Notes
resolve function A function that returns ID of an assignee of your choice
rules array Array of rules (see below)
defaultRules array Pass an empty array to disable your default assignment rules

You can use all three properties: rules, defaultRules and resolve. The priority is as follows:

  1. resolve
  2. rules (recommended)
  3. defaultRules

rules

window.chaportConfig = {
  appId: '<yourAppId>',
  assignments: {
    rules: [
      // assign to the example.com team if a visitor is on example.com
      { 'example.com-team-id': ['page_url', 'contains', 'example.com'] },

      // assign to the sales team if the visitor's role in your system is 'lead' (hypothetical example)
      { 'sales-team-id': function (cp) { return cp.compare(yourUser.role, '=', 'lead') } },

      // assign to the VIP team if your isVIP function returns true
      { 'vip-team-id': function (cp) { return isVIP() } },

      // assign to the US Sales team if visitor's location is US
      { 'us-sales-team-id': ['country', '=', 'US'] },

      // assign to the Spanish support team if visitor's language is Spanish
      { 'es-support-team-id': ['language', '=', 'es'] },

      // assign everything else to John
      { 'john-id': true },
    ],
  },
};

Each array element must be an object with a single key. The key must be an ID of a team or an operator, which should be assigned to a new chat if a visitor matches this rule. The value may be one of these:

  1. a boolean - if true the rule will always apply (useful for a rule applied by default)
  2. an array of this format: [parameterName, matcher, matchValue]
  3. a function that returns true when rule must be applied.

See the example to the right.

defaultRules

window.chaportConfig = {
  appId: '<yourAppId>',
  assignments: {
    defaultRules: [],
  },
};

Primarily useful if you want to disable assignment rules configured in our app.

resolve

window.chaportConfig = {
  appId: '<yourAppId>',
  assignments: {
    resolve: function(cp) {
      // if page url contains example.com
      if (cp.compare(cp.getParameterValue('page_url'), 'contains', 'example.com')) {
        // assign to the example.com team
        return 'example.com-team-id';
      }

      // your can use your own variables for with cp.compare
      if (cp.compare(yourUser.role, '=', 'lead')) {
        return 'sales-team-id';
      }

      // you can check your own conditions for assignment rules
      // NOTE: it assumes that isVIP is your own function
      if (isVIP()) {
        return 'vip-team-id';
      }

      // example using a visitor's country 
      if (cp.compare(cp.getParameterValue('country'), '=', 'US')) {
        return 'us-sales-team-id';
      }

      // example using a user language
      if (cp.compare(cp.getParameterValue('language'), '=', 'es')) {
        return 'es-support-team-id';
      }

      // assign everything else to one of the given operators
      // you can return an array of ids, in which case the chat server will decide which one is going to be assigned
      return ['john-id', 'mary-id'];
    },
  },
};

Define your own function. Return ID of an operator or a team, which should be assigned to a new chat. Return undefined or nothing to continue to the next step. Return null to ignore all other assignment rules.

See the example to the right.

closeButton

Hide the close button.

window.chaportConfig = {
  appId: '<yourAppId>',
  closeButton: false,
};

Optional. Enables you to control whether the close cross should be shown in the widget header. By default, it is shown if the launcher is hidden and on mobile devices where the launcher isn't naturally visible when the widget is expanded. There are however some use cases when default behaviour doesn't produce the desired result, and this option allows you to override it.

countries

Show the chat widget only to US customers.

window.chaportConfig = {
  appId: '<yourAppId>',
  countries: {
    include: ['US'],
  },
};

Optional. Allows hiding the widget for users from specific countries based on IP-address. All countries should be written as a 2-letter ISO code.

Type: object

Property Type Notes
exclude array Array of countries users from which shouldn't see the widget.
include array Array of countries users from which should see the widget. Ignored if exclude is specified.

devices

Nice and easy way to adapt the widget position for a banner on a mobile-only version of your website.

window.chaportConfig = {
  appId: '<yourAppId>',
  devices: {
    configs: {
      mobile: {
        // mobile config override
        // change chat launcher position
        appearance: {
          position: ['right', 0, 50],
        },
      },
    },
  },
};

Optional. Allows providing device-specific configuration options and allows hiding the widget on particular devices.

Type: object

Property Type Notes
exclude array Array of devices that shouldn't display the widget.
include array Array of devices that should display the widget. Ignored if exclude is specified.
configs object Device type specific config overrides

List of supported devices is: desktop, ios, android, mobile (matches both ios and android).

history

Disable changes to browser history by the widget.

window.chaportConfig = {
  appId: '<yourAppId>',
  history: false,
};

Optional. By default, on mobile the widget creates an artificial entry in the browser history when widget is expanded to allow the "Back"-navigation. If you want to disable this behaviour, you can use this option.

init

Wait until the page is loaded, but no longer than 5 seconds before loading the widget.

window.chaportConfig = {
  appId: '<yourAppId>',
  init: {
    event: 'load',
    maxDelay: 5000,
  },
};

Optional. Allows you to delay the widget initialization. Widget can listen for an event and/or set a time delay.

Type: object

Property Type Notes
event string Event name to wait for before initializing the widget.
eventTarget EventTarget An object or an HTML element that will fire the event. Default is window.
maxDelay number A delay in milliseconds after which the widget must be initialized even if the event hasn't yet been emitted.

language

window.chaportConfig = {
  appId: '<yourAppId>',
  language: {
    source: 'html',
  },
};

Optional. Gives control over the language of the widget interface.

Type: object

Property Type Notes
use string Specify a 2-letter language code that you want to use (e.g. "en", "es", etc)
source string Can be either "html" or "header" (default).

If source is "html", preferred language is taken from lang attribute of html tag element (reference).

If source is "header", preferred language is chosen based on Accept-language HTTP header.

source is ignored if use is specified.

launcher

window.chaportConfig = {
  appId: '<yourAppId>',
  launcher: {
    show: false,
  },
};

Optional. Allows changing the launcher.

Type: object

Property Type Notes
show boolean Pass false to hide the default launcher.

openIn

Tell widget to open in a new window

window.chaportConfig = {
  appId: '<yourAppId>',
  openIn: '_blank',
};

Tell widget to open within an element on your page

window.chaportConfig = {
  appId: '<yourAppId>',
  openIn: {
    selector: '#chat-container',
  },
};

Optional. Specify to open the widget in a separate window, tab, iframe or specific element on the page by default.

Type: string | { selector: string }

operators

window.chaportConfig = {
  appId: '<yourAppId>',
  operators: ['operator-id-1', 'operator-name-2'],
};

Optional. Specify to narrow down the list of potential assignees if the visitor starts a chat on this page. Array values can be either operator ids or operator names as provided in the application.

responsive

window.chaportConfig = {
  appId: '<yourAppId>',
  responsive: true,
};

Optional. By default, the widget automatically detects if your website is responsive and acts accordingly on mobile devices.

session

Disable autoStart

window.chaportConfig = {
  appId: '<yourAppId>',
  session: {
    autoStart: false,
  },
};

Later start a session using visitor's credentials stored in their browser

window.chaport.on('ready', function () {
  window.chaport.startSession();
});
window.chaport.q('startSession');

Or using credentials stored on your server after you identified the visitor

window.chaport.on('ready', function () {
  window.chaport.startSession({
    id: 'visitor-id-from-before',
    token: 'visitor-id-token',
  });
});
window.chaport.q('startSession', {
  id: 'visitor-id-from-before',
  token: 'visitor-id-token',
});

Optional. Gives you some control over the way how visitor's credentials are treated. For example, it allows you to identify your visitors and show related chat history, if they are logged in to your website. For more details, please read Logged-in users chapter on how you can take advantage of this feature.

Type: object

Property Type Notes
user object Pass the object containing visitor's id and token like shown in the example. You can retrieve the id by listening to any of these events: 'ready' and 'chat.started'. For more details on tokens read Logged-in users.
autoStart boolean Pass false in order to delay the session start and chat loading until you call startSession method.
persist boolean Pass false to tell the browser not to keep the visitor credentials stored locally

triggers

Disable all triggers

window.chaportConfig = {
  appId: '<yourAppId>',
  triggers: {
    enabled: false,
  },
  // alternatively
  // triggers: {
  //   disabled: true,
  // },
  // or
  // triggers: false,
};

Disable a specific trigger

window.chaportConfig = {
  appId: '<yourAppId>',
  triggers: {
    disabled: ['trigger-id'],
  },
};

Disable all but a specific trigger

window.chaportConfig = {
  appId: '<yourAppId>',
  triggers: {
    enabled: ['trigger-id'],
  },
};

Optional. Allows disabling some or all triggers during initialization. By default, all triggers are enabled. Note: triggers deactivated in the application using a toggle aren't affected by this setting and won't be enabled regardless. If passed with an "enabled" key, all unspecified triggers are disabled.

visitor

window.chaportConfig = {
  appId: '<yourAppId>',
  visitor: {
    name: 'John Doe',
    email: '[email protected]',
    custom: {
      subscriptionPlan: 'pro',
      balance: 1000,
    },
  },
};

Optional. You can use this key to pass your visitor's data during initialization.

Type: object

Property Type Notes
name string full name of the visitor
email string visitor's email
phone string visitor's phone number
notes string notes on the visitor
custom object custom fields

When passing custom fields (i.e., fields having an API key of "custom.*") make sure to put them in a custom object and strip the "custom." part of the key. The example on the right side illustrates it using 2 custom visitor info fields, API keys of these fields are custom.subscriptionPlan and custom.balance.

name, email, phone and notes are create-only unless visitor data is supplemented with a hash.

visitorIntegrityHash

window.chaportConfig = {
  appId: '<yourAppId>',
  visitor: {
    name: 'John Doe',
    email: '[email protected]',
    custom: {
      subscriptionPlan: 'pro',
      balance: 1000,
    },
  },
  visitorIntegrityHash: 'abc123a1b2c3d4e5f6',
};

Optional. Pass the hash to verify the visitor data integrity.

Type: string

Methods

close

window.chaport.on('ready', function () {
  window.chaport.close();
});
window.chaport.q('close');

Collapses the chat widget.

compare

window.chaport.on('ready', function () {
  window.chaport.compare(parameterValue, '=', 'yourValue');
});
window.chaport.q('compare', [parameterValue, '=', 'yourValue']);

Compares two values using one of the available matchers.

Matcher Description
= Checks for equality (case-insensitive for strings)
!= Checks for inequality (case-insensitive for strings)
contains Checks that the 1st string contains the 2nd
!contains Checks that the 1st string doesn't contain the 2nd
gt or > Checks that the 1st number is greater than the 2nd
lt or < Checks that the 1st number is less than the 2nd
gte or >= Checks that the 1st number is greater than or equal the 2nd
lte or <= Checks that the 1st number is less than or equal the 2nd

disableTriggers

Disable all triggers

window.chaport.on('ready', function () {
  window.chaport.disableTriggers();
});
window.chaport.q('disableTriggers');

Disable specific trigger/triggers

window.chaport.on('ready', function () {
  window.chaport.disableTriggers(['trigger-id-1', 'trigger-id-2']);
});
window.chaport.q('disableTriggers', ['trigger-id-1', 'trigger-id-2']);

Disables all or specified triggers. Note that unlike the triggers configuration option, passing specific triggers to this method doesn't enable any other triggers if they were previously disabled.

To also enable all other triggers make sure to call enableTriggers before calling this method.

enableTriggers

Enable all triggers

window.chaport.on('ready', function () {
  window.chaport.enableTriggers();
});
window.chaport.q('enableTriggers');

Enable specific trigger/triggers

window.chaport.on('ready', function () {
  window.chaport.enableTriggers(['trigger-id-1', 'trigger-id-2']);
});
window.chaport.q('enableTriggers', ['trigger-id-1', 'trigger-id-2']);

Enables all or specified triggers. Note that unlike the triggers configuration option, passing specific triggers to this method doesn't disable any other triggers.

To also disable all other triggers make sure to call disableTriggers before calling this method.

getActiveTrigger

window.chaport.on('ready', function () {
  var activeTrigger = window.chaport.getActiveTrigger();
  console.log(activeTrigger);
});
var activeTrigger = window.chaport.q('getActiveTrigger');
console.log(activeTrigger);

Returns a currently active auto-invitation if the chat has not been started yet.

getParameterValue

window.chaport.on('ready', function () {
  var pageUrl = window.chaport.getParameterValue('page_url');
  console.log(pageUrl);
});
window.chaport.on('ready', function () {
  var pageUrl = window.chaport.q('getParameterValue', ['page_url']);
  console.log(pageUrl);
});

Returns value of a parameter, that can be used by auto-invitations, chatbots and assignment rules. Supplements your ability to create your own assignment rules.

When using parameters in your assignment rules or otherwise by calling getParameterValue refer to this table and use a corresponding value in a Key column for the parameter you need.

Name Key
Page URL page_url
Message Text message_text
Country country
Language language
Referrer URL referrer_url
UTM Source utm_source
UTM Medium utm_medium
UTM Term utm_term
UTM Campaign utm_campaign
UTM Content utm_content

getTriggerById

Retrieve text of the auto-invitation by its ID.

window.chaport.on('ready', function () {
  var trigger = window.chaport.getTriggerById('5820a1375ddf087b2e54921d');
  console.log(trigger.message);
});
var trigger = window.chaport.q('getTriggerById', ['5820a1375ddf087b2e54921d']);
console.log(trigger.message);

Returns id and message properties of a matched trigger.

getWidgetState

Automatically close auto-invitation or other message popup after 5 seconds.

window.chaport.on('ready', function () {
  var state = window.chaport.getWidgetState();
  if (['semiExpanded', 'unreadMessage'].indexOf(state) !== -1) {
    setTimeout(function() {
      // before closing, make sure that the state haven't changed while waiting
      var stateNow = window.chaport.getWidgetState();
      if (state === stateNow) {
        window.chaport.close();
      }
    }, 5000);
  }
});
// Command queue interface is not recommended for the cases like this, please use standard Javascript API.

Returns current widget state. The set of possible values is the same as in widget.stateChange callback.

hideLauncher

window.chaport.on('ready', function () {
  window.chaport.hideLauncher();
});
window.chaport.q('hideLauncher');

Hide the default launcher.

isOnline

window.chaport.on('ready', function () {
  window.chaport.isOnline(function (isOnline) {
    console.log(isOnline ? 'Operators are online' : 'Operators are offline');
  });
});
window.chaport.q('isOnline', [function (isOnline) {
  console.log(isOnline ? 'Operators are online' : 'Operators are offline');
}]);

Invokes your callback with a boolean value based on whether any of the operators are online or not.

newPageView

You can pass page details

window.chaport.on('ready', function () {
  window.chaport.newPageView({
    url: 'http://example.com/page2',
    title: 'My test page',
  });
});
window.chaport.q('newPageView', [{
  url: 'http://example.com/page2',
  title: 'My test page',
}]);

Alternatively, current URL and document title are used as page URL and title if omitted.

window.chaport.on('ready', function () {
  window.chaport.newPageView();
});
window.chaport.q('newPageView');

Tells the widget that visitor opened a new page of a single page application.

open

window.chaport.on('ready', function () {
  window.chaport.open();
});
window.chaport.q('open');

Expands the chat widget.

openIn

Open the chat in a new window

window.chaport.on('ready', function () {
  window.chaport.openIn('_blank');
});
window.chaport.q('openIn', [ '_blank' ]);

Open the chat within an element on the page

window.chaport.on('ready', function () {
  window.chaport.openIn({ selector: '#chat-container' });
});
window.chaport.q('openIn', [{ selector: '#chat-container' }]);

Opens the chat in a specified window or within a specified element on the page.

showLauncher

window.chaport.on('ready', function () {
  window.chaport.showLauncher();
});
window.chaport.q('showLauncher');

Show the default launcher.

setActiveTrigger

Activate a custom auto-invitation.

window.chaport.on('ready', function () {
  window.chaport.setActiveTrigger({ message: "Custom message" });
});
window.chaport.q('setActiveTrigger', [{ message: "Custom message" }]);

Activate a modified version of an existing auto-invitation.

window.chaport.on('ready', function () {
  var trigger = window.chaport.getTriggerById('5820a1375ddf087b2e54921d');
  if (!trigger) {
    throw new Error('trigger not found');
  }
  trigger.message = trigger.message.replace('%placeholder1%', 'some text');
  window.chaport.setActiveTrigger(trigger);
});
window.chaport.on('ready', function () {
  var trigger = window.chaport.q('getTriggerById', ['5820a1375ddf087b2e54921d']);
  if (!trigger) {
    throw new Error('trigger not found');
  }
  trigger.message = trigger.message.replace('%placeholder1%', 'some text');
  window.chaport.q('setActiveTrigger', [trigger]);
});

Allows showing a predefined or custom auto-invitation to a visitor.

setAssignmentRules

window.chaport.on('ready', function () {
  window.chaport.setAssignmentRules({
    rules: [
      // assign to the sales team if a visitor is on the pricing page
      { 'sales-team-id': ['page_url', 'contains', 'pricing'] },

      // assign to the sales team if visitor's initial message contains the word "pricing"
      { 'sales-team-id': ['message_text', 'contains', 'pricing'] },

      // assign everything else to the support team
      { 'support-team-id': true },
    ],
    defaultRules: [], // disable default rules
  });
});
window.chaport.q('setAssignmentRules', [{
  rules: [
    // assign to the sales team if a visitor is on the pricing page
    { 'sales-team-id': ['page_url', 'contains', 'pricing'] },

    // assign to the sales team if visitor's original message contains the word "pricing"
    { 'sales-team-id': ['message_text', 'contains', 'pricing'] },

    // assign everything else to the support team
    { 'support-team-id': true },
  ],
  defaultRules: [], // disable default rules
}]);

Allows changing assignment rules after the page has been loaded. It accepts input in the same format as the assignments option.

setVisitorData

window.chaport.on('ready', function () {
  window.chaport.setVisitorData({
    name: 'John Doe',
    email: '[email protected]',
    custom: {
      subscriptionPlan: 'pro',
      balance: 1000,
    },
  }, 'a1b2c3d4e5f6');
});
window.chaport.q('setVisitorData', [ {
  name: 'John Doe',
  email: '[email protected]',
  custom: {
    subscriptionPlan: 'pro',
    balance: 1000,
  },
}, 'a1b2c3d4e5f6' ]);

Sends visitor's data to the server. It accepts the following arguments:

Argument Description
data visitor's data object (same as visitor configuration option)
hash optional argument, pass to verify data integrity

startSession

window.chaport.q('startSession', {
  id: 'visitor-id',
  token: 'visitor-token',
});

Starts a new chat session. If you don't pass visitor credentials as the first argument, the widget will use credentials stored locally on the device (cookies, etc.).

This method is strongly recommended to be used via a Command Queue interface as shown in the example because 'ready' event fires only after the session has already started.

Argument Description
visitorCredentials pass visitor id and token to initiate the chat on behalf of a specific visitor
callback pass a function that needs to be called when the session has started

stopSession

window.chaport.on('ready', function () {
  window.chaport.stopSession();
});
window.chaport.q('stopSession');

Stops a current chat session. Can optionally clear visitor's credentials from the browser, to make sure that the new session will be fresh unless visitor credentials are passed explicitly either as an argument to startSession or session config option.

Argument Description
clearCredentials pass true to "forget" the visitor
callback pass a function that needs to be called when the session has been stopped

toggle

window.chaport.on('ready', function () {
  window.chaport.toggle();
});
window.chaport.q('toggle');

Toggles between expanded and collapsed states. If the widget is in neither (e.g. displays a message), it will expand. This method mimics behavior of a click on the chat launcher button.

updatePosition

window.chaport.on('ready', function () {
  window.chaport.updatePosition(['right', 0, 100], function() {
    console.log('position changed');
  });
});
window.chaport.q('updatePosition', [['right', 0, 100]]);

Allows dynamically changing position of the chat widget.

Argument Description
position pass position in the same format as described in appearance configuration
callback optionally pass a function that needs to be called when the change animation finished

Events

ready

window.chaport.on('ready', listener);
window.chaport.q('on', ['ready', listener]);

Fires after the javascript API becomes available and user session has started right before the widget is rendered.

chat.autoInvitation

window.chaport.on('chat.autoInvitation', function(autoInvitationDetails) {
  console.log(autoInvitationDetails);
});
window.chaport.q('on', ['chat.autoInvitation', function(autoInvitationDetails) {
  console.log(autoInvitationDetails);
}]);

Fires when a new auto-invitation is shown to a visitor (i.e., it doesn't fire when the same auto-invitation re-appears during website navigation).

chat.onlineChange

window.chaport.on('chat.onlineChange', listener);
window.chaport.q('on', ['chat.onlineChange', listener]);

Fires when operators' presence online status changes.

chat.started

window.chaport.on('chat.started', listener);
window.chaport.q('on', ['chat.started', listener]);

Fires when the visitor starts a chat.

widget.stateChange

window.chaport.on('widget.stateChange', listener);
window.chaport.q('on', ['widget.stateChange', listener]);

Fires every time the widget changes the visual state. Possible states are: "expanded", "collapsed", "semiExpanded" (auto-invitation is displayed on desktop), "unreadMessage" (any other unread message - smaller version).

API interfaces

This section covers ways you can interact with the JS API. Use the bar in the top right corner to switch between traditional javascript and command queue examples.

Traditional

This is what a basic traditional usage might look like:

var cpt = window.chaport;
cpt.on('ready', function () {
  cpt.setVisitorData({
    name: 'John Doe',
  });
  cpt.open();
});

Traditional API interface is the interface provided by a vast majority of solutions throughout the internet. You call API methods by calling a co-named method on an exposed object (in our case it's window.chaport). Event handlers are also operated using conventional methods on, off and once. For now, we've only added the on, however, should the need arise we will add off and once too.

Command Queue

This is how a basic command queue usage might look like:

var cpt = window.chaport.q;
cpt('setVisitorData', [{
  name: 'John Doe',
}]);

cpt('open');

Another interface commonly referred to as Command queue is most famously implemented by Google Analytics. It has both pros and cons.

pros:

cons:

Visitor data integrity

How it works

Generate hash on your server (example using PHP for simplicity)

$hash = sha1($yourSalt . json_encode($visitorData));

Pass the hash along with the data

window.chaportConfig = {
  appId: '<yourAppId>',
  visitor: <? echo json_encode($visitorData) ?>,
  visitorIntegrityHash: '<? echo $hash ?>',
}

To protect yourselves from your visitors forging their data via the JS API, you can use visitorIntegrityHash. The hash should be generated on your server using personal salt string, which you can request by sending an email to [email protected].

Without the hash, name, email, phone and notes fields are create-only (i.e., they will only be saved if there is currently no value stored for that particular field).

It is recommended to use the hash.

Transition to using the hash

Below are recommended steps you need to take to start using the hash and ensure the data integrity as pain-free as possible:

  1. Make sure that the visitor's data is passed correctly before requesting the personal salt or passing any hash along.

  2. Request personal salt via an email to [email protected]

  3. Initially, the hash is made optional, and the JS API at this point still allows you to pass data without passing any hash, albeit with named limitations.

  4. Generate and pass the hash. Make sure that any passed data is still properly saved. Important: always generate the hash on your server and never include the personal salt in html/javascript sent to a browser.

  5. Send us a request to make hash required on your account. After the request is processed, visitors will no longer be able to send any forged data using the browser console.

Logged-in users

Help Chaport recognize your logged-in users to make sure that you and they always see the right and full chat history regardless of the device they are using.

To achieve this goal you'll need to perform the following steps:

1. Gather visitor ids by listening to "ready" or "chat.started" event

Add this code right after your installation code (minimalistic example using jQuery)

window.chaport.on('ready', function (data) {
  if (data.visitorId) {
    // send visitor id to your server, example using jQuery
    $.post('/chaport-visitor-id', { chaportVisitorId: data.visitorId })
      .done(function () {
        // server responded with success
      })
  }
})

To identify the visitors you need to keep track of their ids. Recommended way of capturing the visitorId is via either listening to "ready" or "chat.started" events. Having a visitorId send a request with it to your server.

2. Create a controller on your server to handle the request from step #1.

Simple PHP pseudo-code

$chaportVisitorId = isset($_POST['chaportVisitorId']) ? $_POST['chaportVisitorId'] : null;
$loggedInUser = getLoggedInUser(); // pseudo-code for retrieving the data on the logged-in user
if ($chaportVisitorId && $loggedInUser) {
  saveChaportVisitorId($loggedInUser, $chaportVisitorId); // pseudo-code for saving the visitor id in database
}

Handling the request simply retrieve visitorId from the request and store it along with the record of the logged-in user.

3. Add visitor credentials to your installation code if the user is logged in.

Make sure you have access to the currently logged-in user's data

$loggedInUser = getLoggedInUser();

Adjust your installation code to use the visitor id you stored in steps 1 and 2

window.chaportConfig = {
  appId: '<yourAppId>',
  session: {
    user: {
      visitorId: '<? echo $loggedInUser['chaportVisitorId'] ?>',
      token: '<? echo sha1($personalSalt . $loggedInUser['chaportVisitorId']) ?>',
    },
  },
};

Let the widget know the visitor identity of the logged-in user. To retrieve $personalSalt from the example code, please send an email to [email protected].

Feedback

What methods/events you need

Let us know what event or method you are missing!

Your use cases

We are looking to hearing from you about your use cases!

REST API

REST API Overview

Do you want to integrate your backend with Chaport to get visitors' data, chat transcripts and more? Read REST API docs.