The Amazon Connect Chat javascript library (ChatJS) gives you the power to build your own chat widget to customize the chat experience. This can be used for both the agent user interface, in conjunction with Amazon Connect Streams, and for the customer chat interface.
There is a Chat UI reference implementation here. This will help you deploy an API Gateway and Lambda function for initiating chat from your webpage. From there you can use the ChatJS library to build a custom widget.
To learn more about Amazon Connect and its capabilities, please check out the Amazon Connect User Guide.
The AWS-SDK is, by default, included in ChatJS as a "baked-in" dependency. You can view it at ./client/aws-sdk-connectparticipant.js
. In ./client/client.js
we import ConnectParticipant
from this file. This file and import can be removed while using the AWS SDK imported through a script in the page file of your application, assuming that version of the AWS SDK has the ConnectParticipant
service included.
Incidentally, Amazon Connect Streams also contains a "baked-in" AWS SDK. This SDK cannot be removed, as it contains unreleased APIs that will not be available in the SDK you include as a script in the page file.
Therefore, there are several occasions where implementations can run into AWS SDK issues.
Ensure you import ChatJS after Streams.
Import Streams, then ChatJS, then the SDK. Ensure that your AWS SDK includes the ConnectParticipant Service (it is relatively new, so make sure you have an up-to-date AWS SDK version [^2.597.0]).
No need to worry here, this will always work.
Import ChatJS before the AWS SDK, and ensure the AWS SDK version you are using contains the ConnectParticipant Service.
When using the SDK and ChatJS, you may remove the SDK from ChatJS to ensure lack of import conflicts. However, this should not be relevant if the order in which you are importing these libraries is the order reflected above.
npm install amazon-connect-chatjs
import "amazon-connect-chatjs"
Note: this will apply the global connect
variable to your current scope.
amazon-connect-chatjs
is compatible with TypeScript. You'll need to use version 3.0.1
or higher:
import "amazon-connect-streams";
connect.ChatSession.create({ /* ... */ });
$ git clone https://github.com/amazon-connect/amazon-connect-chatjs
- Install latest LTS version of NodeJS
- Checkout this package into workspace and navigate to root folder
npm install
- To build (non-minified):
npm run devo
for a non-minified build.- Find build artifacts in dist directory.
- To build (minified):
npm run release
for a minified build.- Find build artifacts in dist directory.
- To run unit tests:
npm run test
- To clean node_modules:
npm run clean
- To make webpack watch all files:
npm run watch
Find build artifacts in dist directory - This will generate a file called amazon-connect-chat.js
- this is the full Connect ChatJS API which you will want to include in your page.
This is the main entry point to amazon-connect-chatjs
.
All your interactions with the library start here.
connect.ChatSession.setGlobalConfig({
loggerConfig: { // optional, the logging configuration. If omitted, no logging occurs
logger: { // optional, a logger object implementation
debug: (msg) => console.debug(msg), // REQUIRED, can be any function
info: (msg) => console.info(msg), // REQUIRED, can be any function
warn: (msg) => console.warn(msg), // REQUIRED, can be any function
error: (msg) => console.error(msg) // REQUIRED, can be any function
},
level: connect.ChatSession.LogLevel.WARN, // optional, defaults to: `connect.ChatSession.LogLevel.INFO`
},
region: "us-east-1", // optional, defaults to: "us-west-2"
});
Setup the global configuration to use. If this method is not called, the defaults of loggerConfig
and region
are used.
This method should be called before connect.ChatSession.create()
.
const customerChatSession = connect.ChatSession.create({
chatDetails: { // REQUIRED
contactId: "...", // REQUIRED
participantId: "...", // REQUIRED
participantToken: "...", // REQUIRED
},
options: { // optional
region: "us-east-1", // optional, defaults to `region` set in `connect.ChatSession.setGlobalConfig()`
},
type: connect.ChatSession.SessionTypes.CUSTOMER, // REQUIRED
});
Creates an instance of AgentChatSession
or CustomerChatSession
, depending on the specified type
.
If you're creating a CustomerChatSession
, the chatDetails
field should be populated with the response of the StartChatContact API.
If you're creating an AgentChatSession
, you must also include amazon-connect-streams
. For example:
// order is important, alternatively use <script> tags
import "amazon-connect-streams";
import "amazon-connect-chatjs";
connect.contact(contact => {
if (contact.getType() !== connect.ContactType.CHAT) {
// applies only to CHAT contacts
return;
}
// recommended: calls `connect.ChatSession.setGlobalConfig()` and `connect.ChatSession.create()` internally
contact.onAccepted(async () => {
const cnn = contact.getConnections().find(cnn => cnn.getType() === connect.ConnectionType.AGENT);
const agentChatSession = await cnn.getMediaController();
});
// alternative: if you want control over the args of `connect.ChatSession.setGlobalConfig()` and `connect.ChatSession.create()`
contact.onAccepted(() => {
const cnn = contact.getConnections().find(cnn => cnn.getType() === connect.ConnectionType.AGENT);
const agentChatSession = connect.ChatSession.create({
chatDetails: cnn.getMediaInfo(), // REQUIRED
options: { // REQUIRED
region: "us-east-1", // REQUIRED, must match the value provided to `connect.core.initCCP()`
},
type: connect.ChatSession.SessionTypes.AGENT, // REQUIRED
websocketManager: connect.core.getWebSocketManager() // REQUIRED
});
});
});
See the amazon-connect-streams
API documentation for more information on the methods not documented here.
Note: AgentChatSession
and CustomerChatSession
are logical concepts.
As a result, the instanceof
operator will not work how you expect:
if (connect.ChatSession.create(/* ... */) instanceof connect.ChatSession) {
// this will never execute
}
connect.ChatSession.LogLevel = {
DEBUG: /* ... */,
INFO: /* ... */,
WARN: /* ... */,
ERROR: /* ... */
};
Enumerates the logging levels.
connect.ChatSession.SessionTypes = {
AGENT: /* ... */,
CUSTOMER: /* ... */
};
Enumerates the session types.
The ChatSession
API divided into three sections: Amazon Connect Participant Service API wrappers, events, and other.
Functions in this section:
- Wrap the APIs of the Amazon Connect Participant Service.
- Return a
Promise<Response>
(except forchatSession.connect()
), where:Response
is anaws-sdk
Response object.- If the
Promise
rejects, the error will still be aResponse
object. However, thedata
field will not be populated while theerror
field will.
- Can optionally specify a
metadata
arg field (except forcustomerChatSession.disconnectParticipant()
). Themetadata
arg field is not used directly byamazon-connect-chatjs
, rather it's merely copied to the response object for usage by developers.
For example:
function handleResponse(response) {
// `response` is an aws-sdk `Response` object
// `data` contains the response data
// `metadata` === "foo"
const { data, metadata } = response;
// ...
}
function handleError(response) {
// `response` is an aws-sdk `Response` object
// `error` contains the response error
// `metadata` === "foo"
const { error, metadata } = response;
// ...
}
chatSession
.getTranscript({ metadata: "foo" })
.then(handleResponse, handleError);
// connectCalled: indicates whether the Amazon Connect Participant Service was called
// connectSuccess: indicates whether the operation succeeded
const { connectCalled, connectSuccess } = await chatSession.connect();
Wraps the CreateParticipantConnection API.
The arguments and response do not overlap with the API request or response.
Note: If the operation fails, the Promise
will reject, but the error will have the same schema as a successful response.
const awsSdkResponse = await chatSession.getTranscript({
maxResults: 100,
sortOrder: "ASCENDING"
});
const { InitialContactId, NextToken, Transcript } = awsSdkResponse.data;
Wraps the GetTranscript API.
The arguments are based on the API request body with the following differences:
- Fields are in
camelCase
. MaxResults
defaults to15
.ScanDirection
defaults toBACKWARD
always.SortOrder
defaults toASCENDING
.
The response data
is the same as the API response body.
Important note: In order to specify scanDirection
as FORWARD
, you need to explicitly include a startPosition
.
This is because the default startPosition
is at the most recent update to the transcript, so requesting a transcript in the FORWARD
direction from the default startPosition
is equivalent to asking for a transcript containing only messages more recent than the present (you are asking for messages in the future!).
const awsSdkResponse = await chatSession.sendEvent({
contentType: "application/vnd.amazonaws.connect.event.typing"
});
const { AbsoluteTime, Id } = awsSdkResponse.data;
Wraps the SendEvent API.
The arguments are based on the API request body with the following differences:
- Fields are in
camelCase
. ClientToken
cannot be specified.ContentType
allows the following values:"application/vnd.amazonaws.connect.event.chat.ended"
"application/vnd.amazonaws.connect.event.participant.joined"
"application/vnd.amazonaws.connect.event.participant.left"
"application/vnd.amazonaws.connect.event.transfer.succeeded"
"application/vnd.amazonaws.connect.event.transfer.failed"
"application/vnd.amazonaws.connect.event.typing"
The response data
is the same as the API response body.
const awsSdkResponse = await chatSession.sendMessage({
contentType: "text/plain",
message: "Hello World!"
});
const { AbsoluteTime, Id } = awsSdkResponse.data;
Wraps the SendMessage API.
The arguments are based on the API request body with the following differences:
- Fields are in
camelCase
. ClientToken
cannot be specified.
The response data
is the same as the API response body.
// attachment object is the actual file that will be sent to agent from end-customer and vice versa.
const awsSdkResponse = await chatSession.sendAttachment({
attachment: attachment
});
Wraps the StartAttachmentUpload and CompleteAttachmentUpload API. The arguments are based on the StartAttachmentUpload and CompleteAttachmentUpload API request body with the following differences:
- Fields are in
camelCase
. The responsedata
is the same as the StartAttachmentUpload and CompleteAttachmentUpload API response body.chatSession.sendAttachment()
invokes the StartAttachmentUpload API, uploads the Attachment to the S3 bucket using the pre-signed URL received in the StartAttachmentUpload API response and invokes the CompleteAttachmentUpload API to finish the Attachment upload process.
const awsSdkResponse = await chatSession.downloadAttachment({
attachmentId: "string"
});
const { attachment } = awsSdkResponse.data;
/*
Attachment Object - This is the actual file that will be downloaded by either agent or end-customer.
attachment => {
lastModified: long
name: "string"
size: long
type: "string"
webkitRelativePath: "string"
}
*/
Wraps the GetAttachment API. The arguments are based on the API request body with the following differences:
- Fields are in
camelCase
. The responsedata
is the same as the API response body.chatSession.downloadAttachment()
invokes the GetAttachment using the AttachmentId as a request parameter and fetches the Attachment from the S3 bucket using the pre-signed URL received in the GetAttachment API response.
const awsSdkResponse = await customerChatSession.disconnectParticipant();
Wraps the DisconnectParticipant API.
The arguments and response do not overlap with the API request or response.
Once this method is called, the CustomerChatSession
cannot be used anymore.
Applies only for CustomerChatSession
. See connect.ChatSession.create()
for more info.
Function in this section:
- When invoked, register an event handler that is triggered whenever the event occurs.
- Can be called multiple times (i.e. register multiple event handlers).
- Receive an
event
object that contains achatDetails
field. SeechatSession.getChatDetails()
for more info.
chatSession.onConnectionBroken(event => {
const { chatDetails } = event;
// ...
});
Subscribes an event handler that triggers when the session connection is broken.
chatSession.onConnectionEstablished(event => {
const { chatDetails } = event;
// ...
});
Subscribes an event handler that triggers when the session connection is established.
chatSession.onEnded(event => {
const { chatDetails, data } = event;
// ...
});
Subscribes an event handler that triggers when the session is ended.
chatSession.onMessage(event => {
const { chatDetails, data } = event;
switch (data.ContentType) {
// ...
}
});
Subscribes an event handler that triggers whenever a message or an event (except for application/vnd.amazonaws.connect.event.typing
) is created by any participant.
The data
field has the same schema as the Item
data type from the Amazon Connect Participant Service with the addition of the following optional fields: contactId
, initialContactId
.
chatSession.onTyping(event => {
const { chatDetails, data } = event;
if (data.ParticipantRole === "AGENT") {
// ...
}
});
Subscribes an event handler that triggers whenever a application/vnd.amazonaws.connect.event.typing
event is created by any participant.
The data
field has the same schema as chatSession.onMessage()
.
This section contains all the functions that do not fall under the previous two categories.
const {
contactId,
initialContactId,
participantId,
participantToken,
} = chatSession.getChatDetails();
Gets the chat session details.
agentChatSession.cleanUpOnParticipantDisconnect();
Cleans up all event handlers.
Applies only for AgentChatSession
. See connect.ChatSession.create()
for more info.