JavaScript SDK in Live Chat

|

View as Markdown

Use the Live Chat JavaScript SDK to interact with the Live Chat widget in different ways. Every interaction happens through a globally defined function, liveChat, which is available anywhere the widget is initialized.

Select a command in the following table to see its arguments, an example, and details:

CommandPurpose
initInitializes the widget with a widget ID.
authAuthenticates the current user with a JWT.
logoutLogs out an authenticated user and resets the widget to the default state.
clearResets the widget in the same way as logout, for authenticated users and for leads that already have a session.
showShows (expands) the widget.
hideHides (collapses) the widget.
show_launcherShows the widget launcher without expanding the widget.
hide_launcherHides the widget launcher and collapses the widget.
set_themeApplies a theme by theme name. Works only with the legacy widget design.
set_ui_modeSets the light or dark mode of the redesigned widget.
sendSends a basic, draft, or custom data message.
send_contextual_dataSends contextual data (metadata) to a conversation.
set_languageUpdates the widget language and reloads the widget.


The liveChat function [#the-livechat-function]

The definition of the liveChat function in TypeScript syntax is as follows:

liveChat(command: string, arg?: any, callback?: (e?: any, r?: any) => any);

For example, the following snippet initializes the widget:

javascript
1 
2liveChat('init', '85ea1938-f457-496d-8532-8fa489beea63', (error, result) => {
3 if (error) {
4 console.log('init error: ', error);
5 } else {
6 console.log('init result: ', result);
7 }
8});

The snippet has the following parts:

  • liveChat(...);: The global function used to interact with the widget.
  • 'init': The first parameter of the function. This is the command, which tells the widget what to do. In this case, the widget initializes itself. For all commands, see Commands.
  • '85ea1938-f457-496d-8532-8fa489beea63': The second parameter of the function. This is the command argument, or arg. A command can have no argument, an optional argument, or a required argument. The optionality and the type of the argument depend on the command. For details, see Commands.
  • (error, result) => { ... }: The third parameter of the function. This is a callback function, which runs when the command finishes. The callback has two parameters: the first represents an error, and the second represents a result. Only one of them is defined, depending on the execution result. The error parameter is defined in case of failure, and the result parameter is defined in case of success.

On success, the result is null for most commands. For the result of each command, see the Result on success column in the command table.

You can call the liveChat function anywhere in your code after you initialize Live Chat with the snippet from your Infobip account. For how to add the snippet, see Install the web widget.



Commands [#commands]

Each command section lists the argument, an example, and details about the behavior.


Init [#init]

The following table describes the init command:

CommandArgument typeExpected argumentArgument requiredResult on success
'init'stringWidget IDYesnull

Example usage

The following example initializes the widget with a widget ID:

liveChat('init', '85ea1938-f457-496d-8532-8fa489beea63', myInitCallback);

Details

The argument is the ID of the widget that you want to initialize. Call init once per page load, before commands that control the widget, such as show, hide, show_launcher, and hide_launcher. To run them as soon as the widget is ready, call them from the init callback. You can call set_ui_mode, set_language, set_theme, and send_contextual_data before init. The widget applies them when it loads. Before the widget is ready, other commands behave as follows: hide, show_launcher, and hide_launcher fail with error 4002, show is ignored, and send with the DRAFT type fails with error 4003. To initialize a different widget, reload the page.


Auth [#auth]

The following table describes the auth command:

CommandArgument typeExpected argumentArgument requiredResult on success
'auth'stringJWTYesnull

Example usage

The following example authenticates the current user with a JWT that your server generates:

liveChat('auth', fetchTokenFromYourBackend(), myAuthCallback);

Details

This command authenticates the current user with the data provided in the JWT. The system automatically treats users authenticated this way as customers, unless Keep authenticated users as leads is turned on. By authenticating, users verify their identity and can access their previous history.

If the visitor has no open conversation yet, the widget queues the authentication. The callback runs later, when the conversation starts.

For how to generate the JWT, see Generate the personalization token.


Log out [#log-out]

The following table describes the logout command:

CommandArgument typeExpected argumentArgument requiredResult on success
'logout'noneN/ANonull

Example usage

The following example logs out the authenticated user:

liveChat('logout', null, myLogoutCallback);

Details

This command logs out an authenticated user session. You can use it only for authenticated users, so call the Auth command first. When the command runs, the widget reloads and resets to the default state.


Clear [#clear]

The following table describes the clear command:

CommandArgument typeExpected argumentArgument requiredResult on success
'clear'NoneN/ANonull

Example usage

The following example resets the widget:

liveChat('clear', null, myClearCallback);

Details

This command is semantically equivalent to Log out. The only difference is that you can also use clear for leads that already have a session. Without a session, the command fails with error 1321.

NOTEThe optional widget ID argument for the clear command is deprecated and not required. If you provide a widget ID, the command ignores it and behaves as if you called it without a widget ID.

Show [#show]

The following table describes the show command:

CommandArgument typeExpected argumentArgument requiredResult on success
'show'noneN/ANonull

Example usage

The following example shows the widget:

liveChat('show', null, myShowCallback);

Details

This command shows (opens) the widget. If the widget is not expanded yet, it expands.


Hide [#hide]

The following table describes the hide command:

CommandArgument typeExpected argumentArgument requiredResult on success
'hide'noneN/ANonull

Example usage

The following example hides the widget:

liveChat('hide', null, myHideCallback);

Details

This command hides (closes) the widget. If the widget is not collapsed yet, it collapses.


Show launcher [#show-launcher]

The following table describes the show_launcher command:

CommandArgument typeExpected argumentArgument requiredResult on success
'show_launcher'noneN/ANonull

Example usage

The following example shows the widget launcher:

liveChat('show_launcher', null, myShowLauncherCallback);

Details

This command shows the widget launcher but does not expand the widget.


Hide launcher [#hide-launcher]

The following table describes the hide_launcher command:

CommandArgument typeExpected argumentArgument requiredResult on success
'hide_launcher'noneN/ANonull

Example usage

The following example hides the widget launcher:

liveChat('hide_launcher', null, myHideLauncherCallback);

Details

This command hides the widget launcher. If the widget is expanded, it collapses, and the launcher also disappears.


Set theme [#set-theme]

The following table describes the set_theme command:

CommandArgument typeExpected argumentArgument requiredResult on success
'set_theme'stringTheme nameYesName of the applied theme

Example usage

The following example applies the theme named dark:

liveChat('set_theme', 'dark');

Details

This command applies a theme by theme name. You must configure the themes for the widget in your Infobip account, under Channels and Numbers → Channels → Live Chat. For the theme configuration, see Custom themes.

IMPORTANTset_theme works only with the legacy widget design and will be deprecated together with Advanced customization. For the redesigned widget, the command returns the error Command "set_theme" is not supported by the redesigned widget. To change the appearance of the redesigned widget, use Set UI mode.

Set UI mode [#set-ui-mode]

EARLY ACCESS

The following table describes the set_ui_mode command:

CommandArgument typeExpected argumentArgument requiredResult on success
'set_ui_mode'string'light', 'dark', or 'auto'YesThe mode that you set

Example usage

The following example sets each mode:

javascript
1liveChat('set_ui_mode', 'light');
2liveChat('set_ui_mode', 'dark');
3liveChat('set_ui_mode', 'auto');

The following example uses a callback:

javascript
1liveChat('set_ui_mode', 'dark', (error, result) => {
2 if (error) {
3 console.log('set_ui_mode error: ', error);
4 } else {
5 console.log('set_ui_mode result: ', result); // 'dark'
6 }
7});

Details

This command sets the light or dark mode of the redesigned widget, including the chat window, the widget icon, and the eye-catcher. The mode changes immediately. The widget does not reload, and the conversation continues.

The following table describes the supported values:

ValueDescription
'light'Light mode with the light primary color.
'dark'Dark mode with the dark primary color.
'auto'The widget follows the system appearance of the end user (prefers-color-scheme) and changes when the system appearance changes. This is the same as the Match system option in the widget settings. If the browser does not provide the system appearance, the widget uses light mode.

The command behaves as follows:

  • The command overrides the Default theme saved in the widget settings. If you do not call the command, the widget uses the Default theme.
  • You can call the command before or after the Init command. If you call it before init, the widget opens in the selected mode.
  • If you call the command more than once, the widget uses the last valid value.
  • Values are case-sensitive. For any other value, for example 'AUTO', null, or no value, the callback returns the error Invalid UI mode. Expected "light", "dark" or "auto". The widget keeps the current mode.
  • The callback result is the value that you set, for example 'auto'. The result does not show whether the widget displays light or dark mode.
  • The widget keeps the selected mode until the end user leaves or reloads the page. The widget does not save the mode. After the page reloads, the widget uses the Default theme. To use the same mode on every page, call the command on every page load.
  • For widgets that use the legacy design, the command succeeds but does not change the appearance.

The command changes only the widget, not your website:

Website with the Live Chat widget in light mode after liveChat('set_ui_mode', 'light')Website with the Live Chat widget in dark mode after liveChat('set_ui_mode', 'dark')

Send [#send]

The following table describes the send command:

CommandArgument typeExpected argumentArgument requiredResult on success
'send'objectA message payload that determines the message typeYes{message, thread}

Expected argument structure [#send-argument-structure]

The argument is an object that defines the message to send. It supports three payload types: basic, draft, and custom data.

Basic message payload

The basic message payload has the following fields:

FieldTypeRequiredDescription
typestringYesSet to 'BASIC'.
messagestringIf there is no attachmentThe text content of the message.
attachmentstringNoThe attachment content as a data URL with Base64 content, for example data:image/png;base64,.... Links to files are not supported.
fileNamestringIf there is an attachmentThe name of the attachment or file that you send. If you define attachment, define fileName as well.
threadIdstringNoID of the thread to send the message to. If you omit it, the message goes to the active (open) thread for the current user session.

Draft message payload

The draft message payload has the following fields:

FieldTypeRequiredDescription
typestringYesSet to 'DRAFT'.
messagestringYesThe draft message to set in the chat input field.
threadIdstringNoID of the thread to send the message to. If you omit it, the message goes to the active (open) thread for the current user session.

Custom data message payload

The custom data message payload has the following fields:

FieldTypeRequiredDescription
typestringYesSet to 'CUSTOM_DATA'.
customDataobjectYesA structured object that contains custom data relevant to the conversation.
agentMessagestringNoA message displayed to the agent that provides context for the custom data. If undefined, no message is displayed.
userMessagestringNoA message displayed to the user that relates to the custom data. If undefined, no message is displayed.
threadIdstringNoID of the thread to send the message to. If you omit it, the message goes to the active (open) thread for the current user session.

Example usage

The following examples send a basic, a draft, and a custom data message:

liveChat('send', { type: 'BASIC', message: 'Hello! I need help with my order.' }, mySendCommandCallback);

liveChat('send', { type: 'DRAFT', message: 'Hi, I need help with my recent order number:' }, mySendCommandCallback);

liveChat('send', { type: 'CUSTOM_DATA', customData: {'orderId': 'ORD-6789', 'action': 'track_order' }, agentMessage: 'User requested tracking info for order ORD-6789.', userMessage: 'Track my order.' }, mySendCommandCallback);

Details

This command sends a message to a specific thread or to the active (open) thread for the current user session. Depending on the type specified in the payload, you can send the following:

  • Basic message: Plain text messages or file attachments visible to the user and the agent.
  • Draft message: Pre-filled messages in the chat input field. Users can edit the messages before they submit them.
  • Custom data message: Structured data messages with optional visibility for the agent, the user, or both. They support back-end processes without cluttering the chat interface. For more information, see Custom data.

Behavior and thread targeting

The threadId field controls the target thread:

  • If you omit threadId, the message is sent to the active (open) thread in the user session.
  • If you specify a threadId, the message is sent to that thread.

Send contextual data [#send-contextual-data]

The following table describes the send_contextual_data command:

CommandArgument typeExpected argumentArgument requiredResult on success
'send_contextual_data'objectAn object that contains metadataYesnull

Expected argument structure [#send-contextual-data-argument-structure]

The argument is an object with the following fields:

FieldTypeRequiredDescription
metadataobjectYesAn object with key-value pairs that represent the data to send. For example, { 'seconds_since_last_cart_visit': 178 }.
multiThreadStrategystringNoEither 'ACTIVE' or 'ALL'. 'ACTIVE' sends the metadata only to the open active thread. 'ALL' sends the metadata to all threads with active conversations. Applies only to multi-threaded widgets. The default value is 'ACTIVE'.
NOTEWhen you start a chatbot conversation in Live Chat, add a Delay component of at least 1 second before you use metadata in your responses. This gives the metadata time to load fully, because it might not be available at the very start of the conversation.

Example usage

The following example shows the complete argument:

liveChat('send_contextual_data', { metadata: {'color': 'green', 'size': 'M' }, multiThreadStrategy: 'ALL' }, myContextualDataCallback);

Details

This command sends contextual data to a conversation. If you call this command before a conversation starts (usually before the user sends the first message), the contextual data request is queued. The request runs when the widget receives confirmation that the conversation was created.

The queue can cause minor delays between the creation of the conversation and the time it receives the data. If you expect to receive contextual data on conversation creation, take this delay into account.

You can pass any data to a conversation as key-value pairs. For example, a clothing store has Live Chat on its website. A customer who browses the site starts a chat. The website sends all the information about the customer's shopping basket to the agent as the conversation begins. The conversation context card in the agent interface automatically shows all the shared data, so the agent can review it quickly and efficiently.


Set language [#set-language]

The following table describes the set_language command:

CommandArgument typeExpected argumentArgument requiredResult on success
'set_language'stringLanguage tagOptionalnull

Example usage

The following example sets the widget language to Italian (it-IT):

liveChat('set_language', 'it-IT', mySetLanguageCallback);

Details

This command updates the localization of your widget and reloads the widget to apply the updates. If you do not provide a language tag, or if the tag is not supported, the widget defaults to en-US.

Supported languages

The following table lists the supported languages:

Language tagLanguage name
ar-AEArabic
bs-BABosnian
da-DKDanish
de-DEGerman
el-GRGreek
en-USEnglish (United States)
es-ESSpanish (Spain)
es-LASpanish (Latin America)
fr-FRFrench
hr-HRCroatian
hu-HUHungarian
it-ITItalian
ja-JPJapanese
ko-KRKorean
lg-UGLuganda
lt-LTLithuanian
lv-LVLatvian
pl-PLPolish
pt-BRPortuguese (Brazil)
pt-PTPortuguese (Portugal)
ro-RORomanian
ru-RURussian
rw-RWKinyarwanda
sl-SISlovenian
sq-ALAlbanian
sr-LatnSerbian (Latin)
sv-SESwedish
sw-KESwahili (Kenya)
sw-TZSwahili (Tanzania)
th-THThai
tr-TRTurkish
uk-UAUkrainian
zh-HansChinese (Simplified)
zh-HantChinese (Traditional)
zh-TWChinese (Taiwan)


Related pages

Install the web widget
Add the widget snippet to your website and set the widget language.

Authenticate web users
Generate the JWT that you submit with the Auth command.

Appearance
Choose the widget design and the default theme that Set UI mode overrides.

People tracking SDK in Live Chat
Track user activity on Live Chat pages and build person profiles.


Was this page helpful?