NAV Navbar
Javascript Command queue
  • Overview
  • Configuration
  • Methods
  • Events
  • API interfaces
  • Visitor data integrity
  • Logged-in users
  • Feedback
  • REST API
  • Overview

    Scroll down for code samples. Select a language from the tabs above or the mobile navigation menu.

    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 currently available methods, our concerns and more.

    Email: JS API Help

    Installation code looks like this:

    (function(w,d,v3){
    w.chaportConfig = { appId : '<insertYourId>' };
    
    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);
    

    Configuration

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

    appId

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

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

    analytics

    window.chaportConfig = {
      appId: '<yourAppId>',
      analytics: {
        gaTrackerName: 'tracker-1'
      }
    }
    

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

    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.

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

    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 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.

    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.

    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.

    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 (i.e., it is not influenced by auto-invitations).

    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). Same goes for properties (if we happen to add some in future). 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.