NAV
Traditional Command Queue

Overview

Minimal installation code

(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);

More complete example

(function(w,d,v3){
w.chaportConfig = {
  appId : '<insertYourId>',
  language: { // Show widget in english regardless of the user browser language preference
    use: 'en'
  },
  devices: {
    mobile: {
      appearance: { // Shift chat button up on mobile
        position: ['right', 0, 50],
      }
    }
  }
};

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);

window.chaport.on('ready', function() {
  // Below is a hypothetical function to retrieve user details
  getUserDetails(function(userDetails, hash) {
    window.chaport.setVisitorData({ email: userDetails.email, name: userDetails.name }, hash);
  });

  document.querySelector('#your-chat-button').addEventListener('click', function() {
    window.chaport.open();
  });
});
(function(w,d,v3){
w.chaportConfig = {
  appId : '<insertYourId>',
  language: { // Show widget in english regardless of the user browser
    use: 'en'
  },
  devices: {
    mobile: {
      appearance: { // Shift chat button up on mobile
        position: ['right', 0, 50],
      }
    }
  }
};

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);

getUserDetails(function(userDetails, hash) {
  window.chaport.q('setVisitorData', [
    { email: userDetails.email, name: userDetails.name },
    hash
  ]);
});
document.querySelector('#your-chat-button').addEventListener('click', function() {
  window.chaport.q('open');
});

Chaport Javascript API offers control over the chat widget and enables a close integration of Chaport with your application. This documentation covers available configuration options, API methods, and events.

Check out basic usage examples on the right side.

API methods are available through Traditional and Command Queue API interfaces. Use the language toggle in the top right corner to switch examples between them. See API interfaces below.

Email: Javascript API Help

Quickstart

  1. Copy your installation code from Settings → Installation code.
  2. Paste the code into your HTML right before </body>.
  3. (Optional) Configure the widget to window.chaportConfig. See Configuration below.
  4. (Optional) Use the Javascript API to call methods and subscribe to events. See Methods and Events below.

API interfaces

Traditional

Example

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

The Traditional API is the common pattern used by most web integrations: you call methods directly on a global object (in this case, window.chaport).

Use this interface when you need return values or when your code involves branching or more complex logic. Methods are available only after the ready event.

Switch the toggle in the top right corner to Traditional to see examples using this API interface.

Command Queue

Example

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

cpt('open');

The Command Queue API is a pattern popularized by Google Analytics. With Chaport, it lets you queue calls immediately after the installation code — no need to wait for the ready event.

Use this interface for simple, one-way actions (e.g., open, close, setVisitorData). Avoid it in a complex control flow or if you need to use return values.

Switch the toggle in the top right corner to Command Queue to see examples using this API interface.

Command Queue is exposed via a q property under window.chaport.

Configuration

Pass any of the options below in window.chaportConfig.

appId

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

Required. This option is included in the installation code, that you can retrieve at Settings → Installation code. Do not modify it.

analytics

Send events directly to Google Analytics (useful if you load GA via GTM)

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

Use a custom GTM dataLayer variable name

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

Optional. The widget automatically detects Google Analytics on your website even if you don’t provide this option. If you have multiple GA installations/IDs, specify which one to use.

Type: object

Property Type Notes
google object Google Analytics integration configuration
google.id string Google Tag Measurement ID to use when the default ID is not the one you want
google.api string Integration type. One of gtag, gtm, ga, gaq. If omitted, Chaport detects it and prioritizes them in given order
google.apiObject any GA API object if it uses a non-default global name (so it cannot be auto-detected)
google.enabled boolean Set to false to disable sending events to GA

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. Overrides account-level appearance settings on a per-page/per-site basis.

Type: object

Property Type Notes
windowColor string Hex color 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 Welcome text shown when operators are online
offlineWelcome string Welcome text shown when operators are offline
position array Up to 3 elements. The first element is 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 Show message statuses (Unread, Read, Sending) as text (true) or icons (false)

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. Overrides account-level assignment rules. example.com-team-id in the example is either operator or team ID.

Type: object

Property Type Notes
resolve function Pass your custom function to determine an assignee
rules array Assignment rules
defaultRules array Set to [] to disable default assignment rules configured in the app

When multiple properties are provided, priority is:

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

See the sections below to learn more about each property.

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 country is US
      { 'us-sales-team-id': ['country', '=', 'US'] },

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

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

Each array element must be an object with a single key.

  1. boolean — if true, always matches (useful as a fallback)
  2. array[parameterKey, matcher, matchValue]
  3. function — returns true when the rule matches

Also see getParameterValue and compare functions for available parameters and matchers.

defaultRules

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

Set defaultRules: [] to disable assignment rules configured in the Chaport 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';
      }

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

      // Apply your own checks
      if (isVIP()) {
        return 'vip-team-id';
      }

      if (cp.compare(cp.getParameterValue('country'), '=', 'US')) {
        return 'us-sales-team-id';
      }

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

      // Return an array to let the server choose
      return ['john-id', 'mary-id'];
    },
  },
};

Return value:

closeButton

Hide the close button

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

Optional. Controls whether the close (✕) button is shown in the widget header. By default, Chaport shows it when the launcher is hidden and on mobile devices. Use this option to override the default behavior.

countries

Show the chat widget only to visitors from the US

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

Optional. Shows/hides the widget by country based on IP address. Use 2-letter ISO country codes.

Type: object

Property Type Notes
exclude array Countries where the widget should be hidden
include array Countries where the widget should be shown (ignored if exclude is set)

devices

Change widget position on a mobile-only version of your website (e.g., to avoid overlapping a banner)

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

Optional. Applies device-specific configuration and can hide the widget on specific device types.

Type: object

Property Type Notes
exclude array Devices where the widget should be hidden
include array Devices where the widget should be shown (ignored if exclude is set)
configs object Per-device overrides. Each override supports all configuration options in this documentation.

Supported devices: desktop, ios, android, mobile (matches both ios and android).

history

Disable browser history integration on mobile

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

Optional. On mobile, by default Chaport adds a history entry when the widget expands so the browser “Back” button collapses it. Set to false to disable this behaviour.

init

Initialize 0.5s after page load, but no later than 5 seconds (default)

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

Optional. Controls how and when the widget initializes. The default configuration is suitable for most sites. Override it to fine-tune the default behavior (for example, to improve page speed metrics).

Type: object

Property Type Notes
event string Event name to wait for before initializing
eventTarget EventTarget Emitter for event (default: window)
maxDelay number Maximum delay (ms) before forcing initialization
delayAfterEvent number Additional delay (ms) after the event fires

language

Sync the widget UI language with language of your website

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

Use english language regardless of the browser and website languages

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

Optional. Controls the widget UI language.

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", the language is taken from the <html> lang attribute.

If source is "header", the language is derived from the Accept-Language HTTP header.

If use is set, it overrides source.

launcher

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

Optional. Controls the default launcher.

Type: object

Property Type Notes
show boolean Set to false to hide the default launcher

openIn

Open chat in a new window/tab

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

Render chat inside an element on your page

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

Optional. Controls where the widget opens (new window/tab, iframe, or inside a page element) when the launcher is clicked or when calling open().

Type: string | { selector: string }

operators

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

Optional. Limits the operators shown in the widget initially. You can include team IDs to include their members. If you do not use assignment rules, new chats are assigned to one of the listed operators/teams.

responsive

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

Optional. By default, the widget detects whether your site is responsive and adapts behavior on mobile accordingly.

session

Disable automatic session start

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

Manully start a session later using locally stored credentials

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

Optional. Controls how visitor credentials are stored and used. Use this to recognize logged-in users and show correct chat history across different devices. See Logged-in users.

Type: object

Property Type Notes
user object Visitor credentials (id, token). You can retrieve id from the ready or chat.started events. See Logged-in users
autoStart boolean Set to false to delay session start until you call startSession()
persist boolean Set to false to prevent storing credentials locally
cookieDomain string Cookie domain for credentials (useful to track users across subdomains). Set explicitly for multi-part TLDs (e.g. .co.uk).

triggers

Disable all triggers (auto-invitations and chatbots)

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

Disable specific triggers

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

Disable all specific triggers

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

Optional. Allows disabling triggers during initialization. Triggers disabled in the Chaport app remain disabled regardless of this setting.

visitor

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

Optional. Pass visitor 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

For custom fields with API keys like custom.*, pass them under visitor.custom and omit the custom. prefix.

Security rule: Visitor data provided from the browser (including chaportConfig.visitor and setVisitorData) can be modified by the visitor. If you need to trust or update sensitive fields (name, email, phone, notes), sign the data server-side and pass visitorIntegrityHash. If you don't use this hash, to prevent your visitors from fiddling with their identifying chat details the following fields are only accepted if they are currently empty: name, email, phone, and notes. See Visitor Data Integrity.

visitorIntegrityHash

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

Optional. Hash that verifies visitor data integrity.

Type: string

Methods

close

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

Closes the chat widget.

compare

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

Compares two values using a matcher. This is mainly used in custom assignment rules.

Matcher Description
= Equality (case-insensitive for strings)
!= Inequality (case-insensitive for strings)
contains String contains
!contains String does not contain
gt or > Greater than
lt or < Less than
gte or >= Greater than or equal
lte or <= Less than or equal

disableTriggers

Disable all triggers (auto-invitations and chatbots)

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 (auto-invitations and chatbots). Note that unlike the triggers configuration option, passing specific triggers to this method doesn't enable any other triggers if they were previously disabled.

If you need to re-enable all and disable some, call enableTriggers first.

enableTriggers

Enable all triggers (auto-invitations and chatbots)

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 (auto-invitations and chatbots). Note that unlike the triggers configuration option, passing specific triggers to this method doesn't disable any other triggers.

If you need to disable all and enable some, call disableTriggers first.

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 trigger (auto-invitation or chatbot) 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 a parameter value used by auto-invitations, chatbots, and 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 a trigger by ID (auto-invitation or chatbot)

window.chaport.on('ready', function () {
  var trigger = window.chaport.getTriggerById('5820a1375ddf087b2e54921d');
  console.log(trigger);
});
// Avoid Command Queue here: return values are unreliable.
// Use the traditional Javascript API for this method.

Returns an object with id and message (or undefined if not found).

getWidgetState

Auto-close a message popup after 5 seconds

window.chaport.on('ready', function () {
  var state = window.chaport.getWidgetState();
  if (state === 'unreadMessage') {
    setTimeout(function() {
      var stateNow = window.chaport.getWidgetState();
      if (state === stateNow) {
        window.chaport.close();
      }
    }, 5000);
  }
});
// Avoid Command Queue here: return values are unreliable.
// Use the traditional Javascript API for this method.

Returns current widget state. Possible values match widget.stateChange.

hideLauncher

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

Hides 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');
}]);

Calls your callback with boolean indicating if any operators are online.

newPageView

Register new page view with 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',
}]);

Register new page with current URL and document title

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

Notifies the widget that the visitor navigated to a new page in a single-page application (SPA). For normal multi-page sites, this is handled automatically.

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/tab

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

Open the chat inside 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/tab or inside a specified page element.

showLauncher

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

Shows the default launcher.

setActiveTrigger

Show a custom auto-invitation

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

Modify and show an existing trigger

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]);
});

Shows a predefined or custom auto-invitation/chatbot.

setAssignmentRules

window.chaport.on('ready', function () {
  window.chaport.setAssignmentRules({
    rules: [
      { 'sales-team-id': ['page_url', 'contains', 'pricing'] },
      { 'sales-team-id': ['message_text', 'contains', 'pricing'] },
      { 'support-team-id': true },
    ],
    defaultRules: [], // Disable default rules
  });
});
window.chaport.q('setAssignmentRules', [{
  rules: [
    { 'sales-team-id': ['page_url', 'contains', 'pricing'] },
    { 'sales-team-id': ['message_text', 'contains', 'pricing'] },
    { 'support-team-id': true },
  ],
  defaultRules: [], // Disable default rules
}]);

Updates assignment rules after the page has loaded. Input format matches 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 data to the server.

Argument Description
data Visitor data (same structure as visitor option)
hash Optional integrity hash (see Visitor data integrity)

startSession

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

Starts a new chat session. If you omit visitor credentials, Chaport uses locally stored credentials (cookies, etc.).

Use Command Queue for this method whenever possible: ready event fires after the session has already started.

Argument Description
visitorCredentials Visitor id and token
callback Function called after the session has started

stopSession

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

Stops the current chat session. Optionally clears local visitor credentials so the next session starts fresh unless credentials are provided via startSession() or session.

Argument Description
clearCredentials Set to true to forget the visitor on this device
callback Function called after the session has stopped

toggle

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

Toggles the widget between opened and closed states. If the widget is in another state (e.g., showing a message), it expands.

updatePosition

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

Updates widget position dynamically.

Argument Description
position Position in the same format as appearance.position
callback Optional function called when the animation finishes

Events

ready

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

Fires when the Javascript API is available and the 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 an auto-invitation is shown to a visitor for the first time (it does not fire when the same invitation reappears during navigation).

chat.botSent

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

Fires when a chatbot is shown to a visitor for the first time (it does not fire again when the same message reappears during navigation).

chat.onlineChange

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

Fires when operators' online/offline 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 whenever the widget’s visual state changes. Possible values: expanded, collapsed, unreadMessage.

Visitor data integrity

How it works

Generate the hash on your server (. denotes concatenation)

$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 prevent visitors from forging identifying fields via the Javascript API, use visitorIntegrityHash. Generate the hash on your server using a personal salt.

Without the hash, name, email, phone, and notes are only accepted if they are currently empty.

Transition to using the hash

Recommended rollout:

  1. Verify that visitor data is passed correctly without a hash.
  2. Retrieve your personal salt at Settings → API.
  3. Start generating and sending visitorIntegrityHash. At this stage, the hash is still optional — the widget will accept unsigned data, but identifying fields have the usual limitations.
  4. Verify that updates are accepted when a valid hash is present.
  5. Keep the salt server-side only. Never expose it in HTML/Javascript.
  6. Ask Chaport support to make the hash required for your account. Once enabled, visitor data will be accepted only when a valid hash is provided.

Logged-in users

Implement logged-in user identification so you and your visitors see the correct chat history across multiple devices.

1. Capture and store visitor IDs from ready or chat.started

Minimal client 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 })
  }
});

Simple server example using 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
}

Capture and store the visitorId in your database and associate it with your logged-in user.

2. Provide visitor credentials for logged-in users

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

$loggedInUser = getLoggedInUser();

Include credentials in the session config or startSession call

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

Generate the token on your server by hashing the concatenation of personalSalt and visitorId — i.e., the input must be exactly these 2 strings with no separators or extra characters (do not include . or any other delimiter). Your personal salt is available at Settings → API.

Feedback

What methods/events you need

Tell us what method or event you would like to see added.

Your use cases

We’d love to hear about your use cases.

REST API

To integrate your backend with Chaport (visitor data, chat transcripts, and more), see the REST API docs.