NAV

Introduction

This guide will show you how to get started as quickly as possible with the Web SDK from Zendesk Chat. The Web SDK will give businesses and developers the flexibility to build and customize a chat experience that meet their specific design/brand requirements.

To use the SDK, you will need to know web development or have access to developers that can help you build and maintain your custom widget.

Note: By using the Web SDK, you agree to Zendesk's Master Subscription Agreement and API License Agreement.

Sample Application

The Web SDK Sample App repository is a good starting place for:

The sample application is built using React. Please refer to the README to set up the sample application.

Concepts

The Web SDK is a JavaScript library that enables you to build your own chat UI on top of Zendesk Chat's realtime infrastruture and services.

The Web SDK will automatically handle the heavy lifting of maintaining realtime connection with the Zendesk Chat servers as well as taking care of visitor's session for you. It provides a list of events and convenient methods so you can focus on building a highly customized chat UI.

System Requirements for Visitors

When building a custom widget using the Web SDK, the browsers and browser versions that are supported is up to you. However, the Web SDK does require a connection with Transport Layer Security (TLS) 1.2 or above. Older browsers or devices that do not support TLS 1.2 will cause the Web SDK to not initialize properly.

To see what browsers support TLS 1.2, please look at the following link.

To learn what are the general system requirements for Zendesk Chat and the standalone Chat widget, click here.

Relationship with Zendesk Chat Widget

By default, each Zendesk Chat account comes with a default Chat Widget. The appearance and behavior of the Chat Widget can be set through the Zendesk Chat dashboard.

If you decide to build a custom chat widget using the Web SDK, any appearance-related settings for the Zendesk Chat Widget will not be reflected on your chat widget. You are also expected to write your own code to customize the design of the chat widget.

API Methods

The Web SDK maintains a convention on the naming and behavior of the API methods.

The getter methods will synchronously return the latest confirmed information about the requested topic.

For example:

// current visitor's info
console.log(zChat.getVisitorInfo());  // { display_name: 'Jack' }

zChat.setVisitorInfo({ display_name: 'Jane' }, function(err) {
    if (!err) {
        // server has received visitor name update successfully
        console.log(zChat.getVisitorInfo());  // { display_name: 'Jane' }
    }
});

// getting visitor info right after setting
console.log(zChat.getVisitorInfo());  // { display_name: 'Jack' }

On the other hand, the setter methods are asynchronous and follow the Node.js callback style. It accepts an optional callback, which informs you if the API method has been executed successfully. Refer to the Error Handling section for further details.

For example:

zChat.addTag('Sales', function(err) {
    if (err) {
        // Report error here
    }
    else {
        // Do something when tag is added sucessfully
    }
});

A full list of API methods can be found under API Methods.

Event Registry

The Web SDK also provides an event registry where you can listen to specific events when they occur.

function listener(detail) { ... }

// To register your event listener:
zChat.on('event_name', listener);

// To deregister your event listener:
zChat.un('event_name', listener);

A full list of events we support can be found under Events.

Error Handling

There are three types of errors which can occur while using the SDK.

The first type is the validation error. A validation error occurs when API methods are called with parameters which do not conform to the desired format. For example, this can occur when a Number value is passed to an API method which requires String as its parameter type, or when an invalid email is used when invoking zChat.sendEmailTranscript(). When this occurs, the error message related to the API method will be output to the browser's console.

You may choose to suppress these errors by setting suppress_console_error to true when initializing the SDK:

zChat.init({
    account_key            : 'YOUR_ZENDESK_CHAT_ACCOUNT_KEY',
    suppress_console_error : true
});

As an alternative, you may choose to capture these errors using your own error handler by listening to the 'error' event:

var error_handler = function(err) {
    // err is an Error object resulting from a validation error
};

zChat.on('error', error_handler); // Listen to the error event

To avoid this type of errors, be sure to refer to the API Methods section for the required type and description for each parameter.

The second type of error which can occur is when an invocation of an API method did not execute successfully. Whenever this type of errors is anticipated, the API method will accept a callback function, also labelled callback in the API Methods section. The expected signature for the callback function is as follows:

function(err, ...args) { ... }

When an API method is invoked successfully, the err parameter will always be null. Otherwise, it will point to an Error object.

The third type of error that can occur is when the structured message payload received via the 'chat.msg' event is not supported by the correct Web SDK version.

Chat Participants

A chat participant is someone who has participated in a chat session either by joining the chat session or sending a chat message. This includes both the visitor and agents.

A chat participant is identifiable by a unique string property known as nick. For visitors, the nick property will be 'visitor', and for agents it will be in the format of 'agent:<agent-id>'.

Guide

Getting the SDK

The source code of Zendesk Chat Web SDK is a single JavaScript file.

The download URLs for the current and previous releases can be obtained from the Downloads section.

Setting up the SDK

The Zendesk Chat Web SDK can be used in the following ways:

1. CommonJS Module

var zChat = require('/path.to/web_sdk');

2. AMD Module

require(['/path.to/web_sdk'], function(zChat) {
    ...
});

3. HTML Script Tag

 <!-- exposed via window.zChat -->
 <script src="/path.to/web_sdk.js" type="text/javascript"></script>

In the rest of the documentation, we will refer to zChat as the imported Zendesk Chat Web SDK object.

Initializing the SDK

To initialize the SDK, you need to provide your Zendesk Chat account key and run the following code once you have set up the SDK:

zChat.init({
    account_key: 'YOUR_ZENDESK_CHAT_ACCOUNT_KEY'
});

To get your account key, follow these steps:

  1. In the Zendesk Chat Dashboard, click on your profile in the upper right corner and click on the 'Check Connection' option:

    status dropdown

  2. In the dialog, copy the account key value:

    account key

You will also need to wait for the connection to be established before you start consuming the API methods:

zChat.on('connection_update', function(status) {
    if (status === 'connected') {
        // Start consuming your API here
    }
});

Visitor Authentication

The Web SDK allows you to authenticate your visitors using JWT. In order to do so, you need to initialize the Web SDK with the authentication option as follows:

zChat.init({
    account_key: 'YOUR_ZENDESK_CHAT_ACCOUNT_KEY',
    authentication: {
        jwt_fn: function(callback) {
            fetch('JWT_TOKEN_ENDPOINT').then(function(res) {
                res.text().then(function(jwt) {
                    callback(jwt);
                });
            });
        }
    }
});

In the above example, JWT_TOKEN_ENDPOINT is an endpoint which can be implemented on your own server to obtain a fresh JWT for the particular visitor. You may refer to the Creating a JWT token section in this Help Center article for additional information on how you can create your own JWT token.

Certain API Methods may not be available for authenticated visitors or may be available but with reduced functionality, you may find such information under the description of these affected methods.

To log out an authenticated visitor, call zChat.logout(). This will close the connection to the Zendesk Chat server and you will need to re-initialize the Web SDK to establish connection again.

Chat

With the Web SDK, your visitors can chat with your agents in realtime or send offline messages.

Starting a Chat

A chat is a conversation between the visitor and one or more agents who will be communicating with the visitor.

To start a chat, the visitor or an agent needs to send the first message in the chat. When this happens, a 'chat' event of type chat.memberjoin will be fired indicating the the participant who has joined the chat (the participant who sent the first message).

Sending a Chat Message

To send a message, use zChat.sendChatMsg().

Sending Offline Messages

Our Web SDK allows you to send offline messages so that you do not miss messages from your visitors. Use zChat.sendOfflineMsg() to send an offline message.

Ending a Chat

A chat session is ended whenever the visitor leaves the chat.

This can also be triggered programmatically using zChat.endChat().

Typing

Typing indicators allow the visitor or agents to know that the other party is currently typing a message.

To inform the agent that the visitor is currently typing, use zChat.sendTyping(true).

Similarly, use zChat.sendTyping(false) to inform the agent that the visitor is not typing.

On the other hand, you can be notified if an agent is currently typing by listening to the 'chat' event of type typing:

// Listen to the typing event
zChat.on('chat', function(detail) {
    if (detail.type === 'typing') {
        // Agent's typing state
        var is_typing = detail.typing;
    }
});

Last Read Timestamp

Last read timestamps allow agents to see at what point has the visitor read up to in the chat conversation. In the agent chat panel and top bar app for Support integration customers, this is indicated by a double checkmark in the chat log:

last read timestamp

You can update this timestamp by calling zChat.markAsRead() when the visitor interacts with your custom widget, for instance when the text area is clicked, chat log is scrolled to the latest message, etc.

To receive updates on the visitor's last read timestamp, you can listen to the 'chat' event of type last_read:

// Listen to the typing event
zChat.on('chat', function(detail) {
    if (detail.type === 'last_read') {
        // The new last read timestamp
        var timestamp = detail.timestamp;
    }
});

This allows you to synchronize unread message counts for the same visitor across multiple tabs, as well as for authenticated visitors across multiple devices.

Chat Transcript

Visitors can request for the chat transcript to be delivered to their email address.

The chat transcript will be sent to the visitors when the chat session ends.

To do so, use zChat.sendEmailTranscript(email), passing in the visitor's email.

For authenticated visitors with past chats, this method will schedule an email containing the transcript for the most recent conversation.

Chat Feedback

Visitors can give feedback to agents before the chat has ended. Currently, visitors can rate a chat or leave a comment.

To rate a chat:

zChat.sendChatRating('good', function(err) { ... });

To leave a comment:

zChat.sendChatComment('Agent is helpful', function(err) { ... });

Attachments

The Web SDK also supports sending and receiving of file attachments during chat.

Sending Attachments

To send a file attachment, use zChat.sendFile() as shown in the following example:

zChat.sendFile(file, function(err, data) {
    if (!err) {
        // Print out the file's name and URL
        console.log('File name:', data.name);
        console.log('File URL:', data.url);
    }
});

Receiving Attachments

Attachments successfully sent by others will be broadcasted as a chat event. Listen to 'chat' events of type chat.file to get more info.

For example:

zChat.on('chat', function(event_data) {
    if (event_data.type === 'chat.file') {
        // Incoming attachment
        // Attachment's URL
        var url = event_data.attachment.url;
    }
});

Structured Messages

Structured messages are message templates that allow you to provide a richer messaging experience than just pure text.

By incorporating new elements such as one-time-use quick reply buttons, persistent panel templates with embedded pictures, and different button actions, you can use templates for many purposes.

Examples include e-commerce goods recommendation, content recommendations, option selections, and service scheduling.

Where is the structured message payload?

The payload can be found in structured_msg property under the 'chat.msg' event.

What types of structured messages are currently available?

The following structured messages are currently available, along with examples of how these messages can look like when implemented:

  1. Quick Replies

    Quick Replies allows a message to be sent with an array of options for a end-user to choose. Once an option is selected, it can be sent as a reply.

    quick replies

  2. Button Template

    Button Template allows a message to be sent along with a list of buttons. Once the button is selected, it can either

    • make a quick reply
    • open a URL

    button template

  3. Panel Template

    A Panel Template allows a message to be sent with a panel (containing image, title, subtitle) and a list of options as buttons.

    panel template

  4. Panel Template Carousel

    A Panel Template Carousel allows a message to be sent as a carousel of Panel Template.

    panel template carousel

  5. List Template

    A List Template allows a message to be sent with a list of items (containing image, title, subtitle) and a button.

    list template

How can you send a structured message?

Structured messages can only be sent via Chat Conversation API.

Error Handling for Unsuppported Structured Messages

If your current Web SDK version does not support newer structured messages types, an 'error' event will be emitted. Consider upgrading to the latest Web SDK version.

API Reference

This section contains a comprehensive list of the API Methods and Events supported by the Web SDK.

API Methods

The zChat object comes with multiple API methods to send and retrieve chat data.

General style are:

zChat.init(options)

Initializes visitor session and creates connection to Zendesk Chat servers.

Refer to the Initializing the SDK section for details on how to obtain your Zendesk Chat account key.

Arguments:

Parameter Type Required
options Object

Properties of options:

Property Type Required Description
account_key String Your Zendesk Chat account key
suppress_console_error Boolean true to suppress errors from being logged in browser's console, and false if otherwise
Defaults to false if not specified
authentication Object A way to authenticate visitors, currently only JWT is supported

Properties of authentication:

Property Type Required Description
jwt_fn Function A function that accepts a callback. When this function is called, it should retrieve a new JWT and pass the JWT string to the callback as its first argument

Example:

zChat.init({
    account_key            : 'YOUR_ZENDESK_CHAT_ACCOUNT_KEY',
    suppress_console_error : true,
    authentication         : {
        jwt_fn : function(callback) {
            fetch('JWT_TOKEN_ENDPOINT').then(function(res) {
                res.text().then(function(jwt) {
                    callback(jwt);
                });
            });
        }
    }
});

zChat.getAccountStatus()

Returns the current status of the account.

This is a convenience getter for the account_status event.

Format of returned value:

Value Type Description
'online' String Account is online
'away' String Account is away
'offline' String Account is offline

Example:

var account_status = zChat.getAccountStatus();
// 'online'

zChat.getConnectionStatus()

Returns the current state of the connection.

This is a convenience getter for the connection_update event.

Format of returned value:

Value Type Description
'connected' String Connection has been established with Zendesk Chat's backend
'connecting' String Connection is being established
'closed' String Connection has been closed due to various reasons, e.g. banned visitor

Example:

var connection_status = zChat.getConnectionStatus();
// 'connected'

zChat.getVisitorInfo()

Returns the information of the current visitor.

This is a convenience getter for the visitor_update event.

Format of returned object:

Type Description
VisitorInfo Object containing visitor's information

Properties of VisitorInfo object

Property Type Description
display_name String Display name of visitor
email String Email of visitor
phone String Phone number of visitor

Example:

var visitor_info = zChat.getVisitorInfo();
/*
    {
        name  : 'John Doe',
        email : 'john@zendesk.com'
        phone : '12345678'
    }
*/

zChat.setVisitorInfo(options, callback)

Updates current visitor's information.

Arguments:

Parameter Type Required
options Object
callback Function

Properties of options:

Property Type Required Description
display_name String Display name of visitor, maximum length of 255 UTF-16 code units
email String Email of visitor, must be matchable by zChat.EMAIL_REGEX
phone String Phone number of visitor, should be numeric with maximum length of 25 UTF-16 code units

Example:

var visitorInfo = {
    display_name : 'John Doe',
    email        : 'john.doe@zendesk.com'
};

zChat.setVisitorInfo(visitorInfo, function(err) { ... });

zChat.sendVisitorPath(options, callback)

Sends out the visitor's path to the Zendesk Chat server.

This is used to track the visitor's navigation history on your website. It will appear as if the visitor has open a new web page, especially useful for single-page apps.

Arguments:

Parameter Type Required Description
options Object The information about the web page
callback Function Callback function

Properties of options:

Key Type Required Description
title String Title of web page
url String Valid URL of web page

Example:

var newPage = {
    title: 'Pricing',
    url: 'https://example.com/page#pricing'
};

zChat.sendVisitorPath(newPage, function(err) { ... });

zChat.getQueuePosition()

Added in v1.2.0

Returns the visitor's queue position.

If the visitor is not in a queue, this will return 0.

Format of returned value:

Property Type Description
queue_position Integer Visitor's queue position

zChat.getAllDepartments()

Returns an array of the account's departments.

This is a convenience getter for the department_update event.

Format of returned value

Type Description
Array[Department] A list of departments

Format of Department object:

Property Type Description
id Integer ID of department
name String Name of department
status String Status of department, either 'online', 'away' or 'offline'

Example:

var departments = zChat.getAllDepartments();
/*
    [
        {
            id: 1,
            name: 'Marketing'
            status: 'offline'
        },
        {
            id: 2,
            name: 'Sales'
            status: 'online'
        }
    ]
*/

zChat.getDepartment(id)

Returns the information of a particular department based on the given ID.

Arguments:

Parameter Type Required Description
id Integer ID of the department

Example:

var department = zChat.getDepartment(1);
/*
    {
        id: 1,
        name: 'Marketing'
        status: 'offline'
    }
*/

zChat.getVisitorDefaultDepartment()

Returns the ID of the current visitor's default department.

If the visitor's default department is not set, this will return undefined.

Format of returned value:

Property Type Description
id Integer | undefined ID of department

Example:

var department = zChat.getVisitorDefaultDepartment();
/*
    {
        id: 2,
        name: 'Sales'
        status: 'online'
    }
*/

zChat.setVisitorDefaultDepartment(id, callback)

Set the current visitor’s default department.

If the default department is set after chat has already started, it will only take effect on the next chat.

Arguments:

Parameter Type Required Description
id Integer ID of the department
callback Function Callback function

Example:

zChat.setVisitorDefaultDepartment(1, function(err) { ... });

zChat.clearVisitorDefaultDepartment(callback)

Clears the current visitor’s default department. This will only work before the chat starts.

Arguments:

Parameter Type Required Description
callback Function Callback function

Example:

zChat.clearVisitorDefaultDepartment(function(err) { ... });

zChat.sendChatMsg(msg, callback)

Sends a chat message from the current visitor. This should only be used when the account is online.

Arguments:

Parameter Type Required Description
msg String Message to be sent
callback Function Callback function

Example:

zChat.sendChatMsg('hello', function(err) { ... });

zChat.sendFile(file, callback)

Sends a file attachment from the current visitor.

Arguments:

Parameter Type Required Description
file File File attachment to be sent
callback Function Callback function, see below for its signature

The signature of the callback function is

function (err, data) { ... }

Callback error:

When the API fails to complete successfully, an Error object will be passed to the callback function.

The cause of failure can be determined from the error's message property, i.e. err.message.

Error Message Description
"NOT_SUPPORTED" File sending is not supported on this browser (requires FormData basic support)
"NOT_ALLOWED" File sending is not allowed due to account's File Sending settings
"CONN_ERROR" File sending failed due to connectivity issues
"INVALID_EXTENSION" File sending failed due to invalid file extension
"EXCEED_SIZE_LIMIT" File sending failed due to file size exceeding limit
"INTERNAL_ERROR" Zendesk Chat internal error occurred
"UNKNOWN_ERROR" Unknown error occurred

Callback data:

When the API is successfully executed, i.e. err is null, a data object will be returned in the callback with the following properties:

Property Type Description
mime_type String Attachment MIME type (e.g. 'image/png')
name String Attachment name ('screenshot.png')
size Integer Attachment size in bytes (686030)
url String URL to raw attachment file

Example:

zChat.sendFile(file, function(err, data) { ... });

zChat.sendOfflineMsg(options, callback)

Sends a single offline message from the current visitor. This should only be used to send offline messages to an offline account or department.

Arguments:

Parameter Type Required Description
options Object options object, refer below
callback Function Callback function

Properties of options:

Property Type Required Description
name String Name of visitor, maximum length of 255 UTF-16 code units
email String Email of visitor, must be matchable by zChat.EMAIL_REGEX
phone String Phone number of visitor, should be numeric with maximum length of 25 UTF-16 code units
message String Offline message to be sent
department Integer ID of department for the message to be routed to

Example:

zChat.sendOfflineMsg({
    name: 'John',
    email: 'john.doe@zendesk.com',
    phone: '12345678',
    message: 'Please get back to me john.doe@zendesk.com',
    department: 1
}, function(err) {
    ...
});

zChat.addTag(tag, callback)

Adds new visitor tag to the current visitor's session.

Arguments:

Parameter Type Required Description
tag String Tag to be added
callback Function Callback function

Example:

zChat.addTag('pricing', function(err) { ... });

zChat.removeTag(tag, callback)

Removes existing tag from current visitor's session.

Arguments:

Parameter Type Required Description
tag String Tag to be removed
callback Function Callback function

Example:

zChat.removeTag('pricing', function(err) { ... });

zChat.addTags(tags, callback)

Adds new visitor tag(s) to the current visitor's session.

Arguments:

Parameter Type Required Description
tags Array[String] List of tags to be added
callback Function Callback function

Example:

zChat.addTags(['vip', 'premium'], function(err) { ... });

zChat.removeTags(tags, callback)

Removes existing visitor tag(s) from current visitor's session.

Arguments:

Parameter Type Required Description
tags Array[String] List of tags to be removed
callback Function Callback function

Example:

zChat.removeTags(['vip', 'premium'], function(err) { ... });

zChat.sendTyping(is_typing)

Sends the visitor's current typing status to the agents.

Set is_typing as true to indicate that the visitor is currently typing and false otherwise.

Arguments:

Parameter Type Required Description
is_typing Boolean Typing status of visitor

Example:

// Indicate that visitor is typing
zChat.sendTyping(true);

zChat.getChatInfo()

Returns the visitor's rating and/or comment for the current chat.

If the rating or comment is not available for the current chat, the value of the respective property will be null.

Format of returned object:

Type Description
ChatInfo Object containing visitor's rating & comment

Properties of ChatInfo object

Property Type Description Notes
rating String | null Visitor's rating Either 'good', 'bad' or null
comment String | null Visitor's comment

Example:

var chatInfo = zChat.getChatInfo();
/*
    {
        rating  : 'good',
        comment : 'Agent is helpful'
    }
*/

zChat.sendChatRating(rating, callback)

Sends the visitor's rating on the chat experience.

The rating argument can be one of the following values:

Value Description
'good' Visitor is satisfied
'bad' Visitor is unsatisfied
null Visitor is removing the rating

Arguments:

Parameter Type Required Description Notes
rating String Visitor's rating Either 'good', 'bad' or null
callback Function Callback function

Example:

zChat.sendChatRating('good', function(err) { ... });

zChat.sendChatComment(comment, callback)

Sends the visitor's comment on the chat experience.

Arguments:

Parameter Type Required Description
comment String Visitor's comment
callback Function Callback function

Example:

zChat.sendChatComment('Agent is helpful', function(err) { ... });

zChat.isChatting()

Returns a boolean value indicating if there is an ongoing chat with the visitor.

Format of returned value:

Type Description
Boolean true if there is an ongoing chat, and false if otherwise

Example:

if (zChat.isChatting()) {
    // Chat is taking place
}
else {
    // No ongoing chat
}

zChat.getChatLog()

Returns an array of chat log messages in the current chat channel.

This is a convenience getter for the chat event.

Refer to chat event for the payload formats of the possible message types.

zChat.getServingAgentsInfo()

Returns an array of information about the agents who are currently serving in the chat.

This is a convenience getter for the agent_update event.

Format of returned value

Type Description
Array[AgentInfo] A list of agents' information

Properties of AgentInfo

Property Type Description
nick String nick property of the agent
display_name String Name of the agent
avatar_path String URL path to the avatar image of the agent
title String Byline or title of the agent

zChat.getOperatingHours()

Returns an account's operating hours.

If the account's operating hours have never been set, this will return undefined.

Format of returned value

Type Description
OperatingHours | undefined Object containing operating hours information

Properties of OperatingHours object:

Property Type Description
enabled Boolean true if operating hours is enabled
type String 'account' or 'department', depending on the type of operating hours set in dashboard
account_schedule Schedule The account's operating hours schedule, is only set if type is 'account'
department_schedule Object Key-value pairs where keys are department IDs and values are Schedule objects, is only set if type is 'department'
timezone String Timezone of account. List of possible values can be found under the "TZ" column here

Properties of Schedule object:

Property Type Description
0 Array[Period] Operating schedule for Sunday
1 Array[Period] Operating schedule for Monday
2 Array[Period] Operating schedule for Tuesday
3 Array[Period] Operating schedule for Wednesday
4 Array[Period] Operating schedule for Thursday
5 Array[Period] Operating schedule for Friday
6 Array[Period] Operating schedule for Saturday

Properties of Period object:

Property Type Description
start Integer Start of operating period, value refers to number of minutes since midnight
(0 means midnight, 1439 means 23:59)
end Integer End of operating period, value refers to number of minutes since midnight
(0 means midnight, 1439 means 23:59)

Example:

var operating_hours = zChat.getOperatingHours();
/*
    {
        enabled  : true,
        type     : 'department',
        timezone : 'Asia/Singapore',
        department_schedule : {
            123456 : {
                0: [{ start: 123, end: 456}],
                1: [{ start: 123, end: 456}, { start: 567, end: 789}],
                2: [{ start: 123, end: 456}, { start: 567, end: 789}],
                3: [{ start: 567, end: 789}],
                4: [{ start: 234, end: 345}],
                5: [],
                6: [{ start: 456, end: 789}]
            },
            234567 : {
                0: [],
                1: [],
                2: [],
                3: [],
                4: [],
                5: [],
                6: []
            }
        }
    }
*/

zChat.sendEmailTranscript(email, callback)

Schedules an email containing the chat transcript to be sent to email when the chat has ended.

For authenticated visitors with past chats, this method will schedule an email containing the transcript for the most recent conversation.

Arguments:

Parameter Type Required Description
email String A valid email for the chat transcript to be sent to
callback Function Callback function

Example

// Schedules chat transcript to be sent to this email at the end of chat
zChat.sendEmailTranscript('john.doe@zendesk.com', function(err) { ... });

zChat.fetchChatHistory(callback)

Fetches past chats for an authenticated visitor.

Upon calling this method, a request will be made to the server to retrieve the chat history of the visitor.

This API method is paginated internally - this means that the Web SDK maintains a cursor that points to the last chat item which was fetched. When this method is invoked for the first time, the cursor is not set and will fetch chat items from the immediately preceding chat. Successive calls to this method will fetch older past chat items until there are no more items to be fetched. The cursor is reset on page reloads or when the Web SDK is re-initialized by invoking zChat.logout() followed by zChat.init().

When this method is executed successfully, up to 20 past chat items are emitted via the history event in a reverse chronological order (most recent to least recent). The callback will then be invoked to signify that the request has completed and provide information about the number of items fetched and if there are more items to be fetched.

When the has_more property of data returned in the callback is false, you should not invoke this method again as it will lead to error.

Additionally, this API method only supports 1 concurrent request at one time. Ensure that you wait for the callback to be invoked before calling it again.

Arguments:

Parameter Type Required Description
callback Function Callback function which is invoked when the request is completed. This function should accept two arguments, error and data

Properties of data object:

Property Type Description
count Integer The number of past chat messages fetched
has_more Boolean Whether there are more past chat messages to be fetched with subsequent zChat.fetchChatHistory(callback) calls

Example

zChat.fetchChatHistory(function(err, data) {
    if (!err) {
        console.log('Number of items fetched', data.count);
        console.log('Has more items to fetch', data.has_more);
    }
});

zChat.markAsRead()

Updates the last read timestamp with the current server timestamp.

Example

zChat.markAsRead();

zChat.reconnect()

Reconnects the visitor's connection when it is disconnected due to idle timeout or intermittent connection.

Example

zChat.reconnect();

zChat.endChat(options, callback)

Ends the current chat session.

Arguments:

Parameter Type Required Description
options Object options object, refer below
callback Function Callback function

Properties of options:

Property Type Required Description
clear_dept_id_on_chat_ended Boolean true to use visitor's default department on new chats, and false to continue using the same department as the previous chat
Defaults to false if not specified

Example

var clearDeptId = {
    clear_dept_id_on_chat_ended: true
};

zChat.endChat(clearDeptId, function (err) {...});

zChat.logout()

Logs out an authenticated visitor.

Upon calling this method, the connection will be closed. You will receive a connection_update event with the closed state.

Most APIs will not be available and will result in error after logout until the Web SDK is re-initialized. The custom widget should also prevent further user actions which can result in invocation of the Web SDK APIs until the re-initialization happens.

If you want to re-initialize the Web SDK, ensure that you call zChat.init() again.

Example

zChat.logout();

Constants

This section contains a comprehensive list of the constants exposed by the Web SDK.

zChat.EMAIL_REGEX

The Email parsing Regex object used to validate all email strings provided to the Web SDK. There might be additional validation layers in the backend which will be surfaced via the err callbacks.

Events

Realtime chat events will be emitted via zChat object. Use zChat.on() and zChat.un() to register event handlers.

zChat.on(event_name, handler)

Register an event handler to an event type.

The handler will have the signature function(event_data).

Arguments

Parameter Type Required Description
event_name String Event name to bind to
handler Function Function with the signature function(event_data)

Example

var handler = function(conn_status) { ... };
// Register an event handler to the connection_update event
zChat.on('connection_update', handler);

zChat.un(event_name, handler)

De-register an event handler from an event type.

Arguments

Parameter Type Required Description
event_name String Event name to unbind from
handler Function Event handler which was previously registered

Example

// De-register event handler from the connection_update event
zChat.un('connection_update', handler);

'account_status' event

This event will be fired when the account's status changes.

Possible values of event_data:

Value Description
'online' Account is online
'away' Account is away
'offline' Account is offline

Example:

zChat.on('account_status', function(event_data) {
    ...
});

'connection_update' event

This event will be fired when the connection to a Zendesk Chat server changes.

Possible values of event_data:

Value Description
'connecting'
  • Connection is being established
  • Data (including chat messages & events) may be outdated
  • New events may be fired
  • 'connected'
  • Connection is fully established
  • Data (including chat messages & events) are up-to-date
  • New events may be fired
  • 'closed'
  • Connection has been closed due to various reasons, e.g. banned visitor
  • Data (including chat messages & events) may be outdated
  • New events will not be fired
  • Example:

    zChat.on('connection_update', function(event_data) {
        ...
    });
    

    'department_update' event

    This event will be fired when status of any department changes.

    Payload of event_data:

    Type Description
    Department A Department object

    Properties of Department object:

    Property Type Description
    id Integer ID of department
    name String Name of department
    status String Status of department, either 'online', 'away' or 'offline'

    Example:

    zChat.on('department_update', function(event_data) {
        ...
    });
    

    'visitor_update' event

    This event will be fired when visitor's information changes, for instance when the visitor joins the chat.

    Payload of event_data:

    Type Description
    VisitorInfo Object containing visitor's information

    Properties of VisitorInfo

    Property Type Description
    display_name String Display name of visitor
    email String Email of visitor
    phone String Phone number of visitor

    Example:

    zChat.on('visitor_update', function(event_data) {
        ...
    });
    

    'agent_update' event

    This event will be fired when an agent's information changes, for instance when an agent joins the chat.

    Payload of event_data:

    Type Description
    AgentInfo Object containing visitor's information

    Properties of AgentInfo

    Property Type Description
    nick String nick property of the agent
    display_name String Name of the agent
    avatar_path String URL path to the avatar image of the agent
    title String Byline or title of the agent

    Example:

    zChat.on('agent_update', function(event_data) {
        ...
    });
    

    'chat' event

    This event consists of all events which are related to the ongoing chat.

    The event_data passed into the handler will contain a type property to indicate the specific type of chat event. Depending on the value of the type property, the event_data objects will have different structures.

    Furthermore, the event_data also contains a nick property to indicate whether it is a visitor or an agent who has triggered this event. For more details on the format of the nick property, refer to Chat Participants.

    The list of possible chat event types are shown in the table below:

    type Description
    'chat.msg' When chat message arrives
    'chat.file' When a file attachment arrives
    'chat.queue_position' When the visitor's queue position is changed
    'chat.memberjoin' When visitor/agent joining the chat
    'chat.memberleave' When visitor/agent leaving the chat
    'chat.request.rating' When agent requests for rating
    'chat.rating' When visitor updates chat rating
    'chat.comment' When visitor updates chat comment
    'typing' When agent starts/stops typing
    'last_read' When visitor's last read timestamp is updated
    'chat.wait_queue' (Deprecated) When the visitor is in a wait queue

    chat.msg Chat event type

    This chat event will be fired when a chat message arrives.

    The event_data will have its type property set to 'chat.msg'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.msg'
    nick String nick property of sender
    display_name String Display name of sender
    timestamp Integer Server timestamp of the message in ms
    msg String Content of the message
    options Array[String] List of options when message is sent by agent using a shortcut
    structured_msg Structured Message Structure message payload. Supported in SDK version 1.6.0 or later. See Structured Message.

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.msg') {
            // ...
        }
    });
    

    chat.file Chat event type

    This chat event will be fired when a new chat attachment is appended to the chat log.

    The event_data will have its 'type' property set to 'chat.file'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.file'
    nick String nick property of sender
    display_name String Display name of sender
    timestamp Integer Server timestamp of the message in ms
    attachment Attachment See below for more information
    deleted Boolean Whether the attachment has been deleted (Only on history event)

    Properties of Attachment object:

    Property Type Description
    metadata Metadata | undefined See below for more information.
    NOT guaranteed to be present even for images
    mime_type String Attachment MIME type (e.g. 'image/png')
    name String Attachment name ('screenshot.png')
    size Integer Attachment size in bytes (686030)
    url String URL to raw attachment file

    Properties of Metadata object:

    Property Type Description
    width Integer Width of the image in pixels
    height Integer Height of the image in pixels

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.file') {
            // ...
        }
    });
    

    chat.wait_queue Chat event type

    This chat event will be fired when the visitor is put in the wait queue if the agents are currently at their capacity.

    The event_data will have its type property set to 'chat.wait_queue'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.wait_queue'
    nick String Always 'system:queue'
    wait_queue Integer The position of the visitor in the wait queue

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.wait_queue') {
            // ...
        }
    });
    

    chat.queue_position Chat event type

    Added in v1.2.0

    This chat event will be fired whenever the visitor's queue position is changed.

    The event_data will have its type property set to 'chat.queue_position'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.queue_position'
    nick String Always 'system:queue'
    queue_position Integer The position of the visitor in the wait queue, or 0 if visitor is not in queue.

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.queue_position') {
            // ...
        }
    });
    

    chat.memberjoin Chat event type

    This chat event will be fired when either the visitor or the agent joins the chat.

    The event_data will have its type property set to 'chat.memberjoin'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.memberjoin'
    nick String nick property of the agent/visitor
    display_name String Display name of the agent/visitor
    timestamp Integer Server timestamp of the message in ms

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.memberjoin') {
            // ...
        }
    });
    

    chat.memberleave Chat event type

    This chat event will be fired when either the visitor or the agent leaves the chat.

    The event_data will have its type property set to 'chat.memberleave'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.memberleave'
    nick String nick property of the agent/visitor
    display_name String Display name of the agent/visitor
    timestamp Integer Server timestamp of the message in ms

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.memberleave') {
            // ...
        }
    });
    

    chat.request.rating Chat event type

    This chat event will be fired when the agent requests for rating from the visitor.

    The event_data will have its type property set to 'chat.request.rating'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.request.rating'
    nick String nick property of the agent
    display_name String Display name of the agent
    timestamp Integer Server timestamp of the message in ms

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.request.rating') {
            // ...
        }
    });
    

    chat.rating Chat event type

    This chat event will be fired when the visitor updates the chat rating.

    The event_data will have its type property set to 'chat.rating'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.rating'
    nick String Always 'visitor'
    display_name String Display name of the visitor
    timestamp Integer Server timestamp of the message in ms
    rating String | undefined Previous rating value ('good' | 'bad')
    new_rating String | undefined New rating value ('good' | 'bad')

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.rating') {
            // ...
        }
    });
    

    chat.comment Chat event type

    This chat event will be fired when the visitor updates the chat comment.

    The event_data will have its type property set to 'chat.comment'.

    Payload of event_data:

    Property Type Description
    type String Always 'chat.comment'
    nick String Always 'visitor'
    display_name String Display name of the visitor
    timestamp Integer Server timestamp of the message in ms
    comment String | undefined Previous comment value
    new_comment String | undefined New comment value

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'chat.comment') {
            // ...
        }
    });
    

    typing Chat event type

    This chat event will be fired when the agent starts or stops typing.

    The event_data will have its type property set to 'typing'.

    Payload of event_data:

    Property Type Description
    type String Always 'typing'
    nick String nick property of agent
    typing Boolean true if agent starts typing and false if otherwise

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'typing') {
            // ...
        }
    });
    

    last_read Chat event type

    Added in v1.7.0

    This chat event will be fired when the last read timestamp is updated.

    The event_data will have its type property set to 'last_read'.

    Payload of event_data:

    Property Type Description
    type String Always 'last_read'
    nick String nick property of sender
    timestamp Integer Server timestamp of the message in ms

    Example:

    zChat.on('chat', function(event_data) {
        if (event_data.type === 'last_read') {
            // ...
        }
    });
    

    'history' event

    This event consists of all events which are related to chat history.

    The event_data passed into the handler will contain a type property to indicate the specific type of chat event. Depending on the value of the type property, the event_data objects will have different structures.

    Furthermore, the event_data also contains a nick property to indicate whether it is a visitor or an agent who has triggered this event. For more details on the format of the nick property, refer to Chat Participants.

    The list of possible history event types are shown in the table below which mostly follows the chat event types' specifications:

    type Description
    'chat.msg' When chat message arrives
    'chat.file' When a file attachment arrives
    'chat.memberjoin' When visitor/agent joining the chat
    'chat.memberleave' When visitor/agent leaving the chat
    'chat.request.rating' When agent requests for rating
    'chat.rating' When visitor updates chat rating
    'chat.comment' When visitor updates chat comment

    Example:

    zChat.on('history', function(event_data) {
        if (event_data.type === 'chat.msg') {
            // ...
        }
    });
    

    'error' event

    This event will be fired when a validation error occurs.

    Refer to the Error Handling section for further explanation on validation errors.

    The Error object has additional properties to indicate the method which triggered the error as well as any extra information on the error. See below for the expected format.

    Payload of event_data:

    Type Description
    Error A JavaScript Error object

    Additional properties on Error:

    Property Type Description
    context String Method name which triggered the error, e.g. 'sendChatMsg' or unsupported structured message found in 'chat.msg' event
    extra Any Extra information on the error, if any

    Example:

    zChat.on('error', function(event_data) {
        ...
    });
    

    Downloads

    For the latest version, download it from https://dev.zopim.com/web-sdk/latest/web-sdk.js.

    For a specific version, refer below:

    Version Download URL
    1.11.2 https://dev.zopim.com/web-sdk/1.11.2/web-sdk.js
    1.11.1 https://dev.zopim.com/web-sdk/1.11.1/web-sdk.js
    1.11.0 https://dev.zopim.com/web-sdk/1.11.0/web-sdk.js
    1.10.0 https://dev.zopim.com/web-sdk/1.10.0/web-sdk.js
    1.9.0 https://dev.zopim.com/web-sdk/1.9.0/web-sdk.js
    1.8.1 https://dev.zopim.com/web-sdk/1.8.1/web-sdk.js
    1.8.0 https://dev.zopim.com/web-sdk/1.8.0/web-sdk.js
    1.7.0 https://dev.zopim.com/web-sdk/1.7.0/web-sdk.js
    1.6.0 https://dev.zopim.com/web-sdk/1.6.0/web-sdk.js
    1.5.0 https://dev.zopim.com/web-sdk/1.5.0/web-sdk.js
    1.4.0 https://dev.zopim.com/web-sdk/1.4.0/web-sdk.js
    1.3.0 https://dev.zopim.com/web-sdk/1.3.0/web-sdk.js
    1.2.0 https://dev.zopim.com/web-sdk/1.2.0/web-sdk.js
    1.1.4 https://dev.zopim.com/web-sdk/1.1.4/web-sdk.js
    1.1.3 https://dev.zopim.com/web-sdk/1.1.3/web-sdk.js
    1.1.2 https://dev.zopim.com/web-sdk/1.1.2/web-sdk.js
    1.1.1 https://dev.zopim.com/web-sdk/1.1.1/web-sdk.js
    1.1.0 https://dev.zopim.com/web-sdk/1.1.0/web-sdk.js
    1.0.1 https://dev.zopim.com/web-sdk/1.0.1/web-sdk.js
    1.0.0 https://dev.zopim.com/web-sdk/1.0.0/web-sdk.js

    Changelog

    Version 1.11.2 - 2020-04-23

    Fixed a potential issue on versions 1.11.0 and 1.11.1 that causes an exception to be thrown when accounts on the new Zendesk Agent Workspace call the zChat.getOperatingHours API.

    Version 1.11.1 - 2020-03-12

    Fixed excessive warnings in the console for accounts using Zendesk Agent Workspace.

    Version 1.11.0 - 2020-02-25

    Updated the following APIs to cope with Support group IDs for accounts using Zendesk Agent Workspace. Other accounts are not affected. Please refer to documentation of the following APIs for more details.

    Version 1.10.0 - 2020-01-22

    Support for upcoming changes to Chrome's SameSite cookie support. To learn more about the changes in Chrome, go to https://www.chromium.org/updates/same-site.

    Added ability to start new chats with different departments, without a page change after ending chat, via clear_dept_id_on_chat_ended option in zChat.endChat(). New chats will then start with visitor's default department.

    Minor bug fixes.

    Version 1.9.0 - 2019-06-20

    Improved connection logic and performance to Zendesk Chat backend servers.

    Minor bug fixes.

    Version 1.8.1 - 2019-03-12

    Fixed connection issues in Internet Explorer 11.

    Improved performance when used across page navigations and with multiple tabs/windows.

    Version 1.8.0 - 2019-02-21

    Added new List Template type for structured messages.

    Made authenticated visitor flow more friendly with CSP.

    Updated zChat.sendOfflineMsg to support empty phone field.

    Updated zChat.reconnect so that it only works when connection status is closed, otherwise it is a noop. The Web SDK has always been attempting to reconnect without any user intervention for all other statuses, for example: network outage.

    Visitor banned status is now remembered for a short period, subsequent zChat.init will be a noop for the duration.

    Version 1.7.0 - 2019-01-10

    Fixed zChat.EMAIL_REGEX where it was previously throwing error when called.

    Added zChat.markAsRead and last_read chat event type. For more details, refer to the Last Read Timestamp section in Guide.

    Added new Panel Template Carousel type for structured messages.

    Version 1.6.0 - 2018-12-07

    Added support for structured messages.

    Added zChat.addTags and zChat.removeTags for bulk addition and removal of tags. Existing APIs for manipulating tags zChat.addTag and zChat.removeTag are deprecated and will be removed in future releases.

    Updated zChat.sendOfflineMsg to support phone field.

    Added limitation on maximum length allowed for certain fields in the following APIs:

    Version 1.5.0 - 2018-07-31

    Added ability to retrieve chat history via zChat.fetchChatHistory() for authenticated visitors.

    Version 1.4.0 - 2018-05-29

    Added ability to authenticate visitors via authentication option in zChat.init() and log out visitors via zChat.logout().

    Added zChat.EMAIL_REGEX constant to expose Email parsing Regex object.

    Added additional context in the 'error' event.

    Added metadata property in 'chat.file' chat event to possibly include dimensions for image attachments.

    Updated zChat.sendEmailTranscript to allow authenticated visitors with past chats to request for email transcript.

    Removed callback parameter from zChat.sendTyping.

    Version 1.3.0 - 2018-01-30

    Improved connection_update event.

    The connection_update event will now be triggered and set to 'connecting' when the connection is disrupted.

    This makes it clearer that the SDK will always attempt to re-establish connection with the server when disconnected.

    Version 1.2.0 - 2017-10-10

    Deprecated chat.wait_queue chat event type. It will eventually not get fired anymore.

    Added chat.queue_position chat event type and zChat.getQueuePosition().

    Version 1.1.4 - 2017-08-02

    Increased maximum file upload size from 5MB to 20MB.

    Version 1.1.3 - 2017-04-05

    Minor stability and reliability fixes.

    Version 1.1.2 - 2017-02-07

    Performance improvements and more bug fixes.

    Version 1.1.1 - 2017-01-09

    Minor bug fix.

    Version 1.1.0 - 2016-11-16

    Added sendFile API to support sending of file attachments.

    Version 1.0.1 - 2016-10-19

    Fixed a bug where zChat.setVisitorInfo() was not setting visitor display name correctly.

    Version 1.0.0 - 2016-10-03

    Initial Web SDK release.