class Session

A session represents a user's active browser tab. It also authenticates your app with TalkJS.

Methods

Constructor

Creates a TalkJS Session.

createChatbox

Creates a Chatbox UI

createInbox

Creates an Inbox UI

createPopup

Creates a Popup UI

destroy

Disconnects all websockets, removes all UIs, and invalidates this session. You cannot use any objects that were created in this session after you destroy it. If you want to use TalkJS after having called destroy() you must instantiate a new Talk.Session instance.

getOrCreateConversation

A method used to either fetch or create a conversation.

getOrStartConversation

Deprecated.

hasValidCredentials

Verifies whether the appId is valid.

off

Used to stop listening to specific TalkJS session events

on

Used to listen to TalkJS session events

registerDevice

Registers mobile device, one user can be connected to one mobile device.

setDesktopNotificationEnabled

Sets desktop notification on or off.

syncThemeForLocalDev

Used to configure TalkJS to use a theme hosted on the same location as your application for development.

unregisterDevice

Unregisters mobile device, one user can be connected to one mobile device.

Properties

appId
string
Your TalkJS AppId that can be found your TalkJS dashboard.
me
The TalkJS User associated with the current user in your application.
unreads
Holds information about unread conversations. Lets your app be notified when the active user receives a new message.

Method Details

Constructor

new Session(options)

Creates a TalkJS Session.

Parameters

options

interface SessionOptions

appId
string
Your app's unique TalkJS id. Get it from the dashboard.
me
A User object that identifies the currently active user. The user is uniquely identified by their id; all other fields (name, photo, etc) are overwritten in the TalkJS database each time they change. Alternatively, only pass a user ID (as a string) if you are certain that the user object exists.
signature
string

optional
If you use Identitiy verification make sure you generate and use a signature.

createChatbox

session.createChatbox(selectedConversation, options): Chatbox

Creates a Chatbox UI

The Chatbox is a slimmer version of the Inbox. It shows a single conversation, without a means to switch between conversations. You typically want to call the mount method after creating the Chabox to make it visible on your app.

Call createChatbox on any page you want to show a chatbox of a single conversation.

Parameters

selectedConversation

Select the conversation to show in the UI.

options

optional

Optional. Use these to finetune the behavior of the Chatbox.

interface ChatboxOptions

chatSubtitleMode
"subject" | "participants" | null

optional
Controls what text appears in the chat subtitle, right below the chat title. No subtitle is displayed when the conversation has no subject set or when set to null. Defaults to "subject". (also see chatTitleMode and InboxOptions.feedConversationTitleMode)
chatTitleMode
"subject" | "participants"

optional
Controls what text appears in the chat title, in the header above the messages. Defaults to "participants". (also see chatSubtitleMode and InboxOptions.feedConversationTitleMode)
dir
"rtl" | "ltr"

optional
Controls the text direction (for supporting right-to-left languages such as Arabic and Hebrew). TalkJS tries to determine the appropriate text direction from the parent page, but if that does not work or you want to explicitly control it, you can override it here. Defaults to "rtl".
messageField

optional
Settings that affect the behavior of the message field
messageFilter

optional
Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes. See MessagePredicate for all available options. You can also modify the filter on the fly using Chatbox.setMessageFilter.
messageSuggestion
string

optional
Sets the message input box to the given text. You can use this to suggest a certain initial message to be sent. The user can still edit it before hitting "send".
showChatHeader
boolean

optional
Used to control if the Chat Header is displayed in the UI. Defaults to true.
thirdparties

optional
TalkJS leverages iframes behind the scenes and therefore not all services that you use in your app will work out of the box. This option adds support for a number of services to help you use them. Let us know if you're missing any.
translateConversations
boolean | string[] | ConversationBuilder[]

optional
TalkJS can translate conversations to the current user's locale using Google Translate. This option specifies which conversations should be translated in this UI. You can pass a boolean to enable/disable translation for all conversations, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the enterprise plan. Make sure you add your Google API key in the dashboard.

Returns

Chatbox

createInbox

session.createInbox(options): Inbox

Creates an Inbox UI

The Inbox is the main UI component of TalkJS. It shows a user's conversation history and it allows them to write messages. You typically want to call the mount method after creating the Inbox to make it visible on your app.

Call createInbox on the messaging page of your app.

Parameters

options

optional

Optional. Use these to finetune the behavior of the Inbox.

interface InboxOptions

chatSubtitleMode
"subject" | "participants" | null

optional
Controls what text appears in the chat subtitle, right below the chat title. No subtitle is displayed when the conversation has no subject set or when set to null. Defaults to "subject". (also see chatTitleMode and feedConversationTitleMode)
chatTitleMode
"subject" | "participants"

optional
Controls what text appears in the chat title, in the header above the messages. Defaults to "participants". (also see chatSubtitleMode and feedConversationTitleMode)
dir
"rtl" | "ltr"

optional
Controls the text direction (for supporting right-to-left languages such as Arabic and Hebrew). TalkJS tries to determine the appropriate text direction from the parent page, but if that does not work or you want to explicitly control it, you can override it here. Defaults to "rtl".
feedConversationTitleMode
"participants" | "subject" | "auto"

optional
Controls how a chat is displayed in the feed of chats. Note: when set to "subject" but a conversation has no subject set, then TalkJS falls back to "participants". When not set, defaults to "auto", which means that in group conversations that have a subject set, the subject is displayed and otherwise the participants. (also see chatSubtitleMode and chatTitleMode)
feedFilter

optional
Used to control which conversations are shown in the conversation feed, depending on access level, custom conversation attributes or message read status. See ConversationPredicate for all available options. You can also modify the filter on the fly using Inbox.setFeedFilter.
messageField

optional
Settings that affect the behavior of the message field
messageFilter

optional
Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes. See MessagePredicate for all available options. You can also modify the filter on the fly using Inbox.setMessageFilter.
messageSuggestion
string

optional
Sets the message input box to the given text. You can use this to suggest a certain initial message to be sent. The user can still edit it before hitting "send".
selected
Conversation | ConversationBuilder | string | null

optional
Makes the inbox start up with the given Conversation. Can be passed a value of the type ConversationBuilder (returned by getOrCreateConversation), the string value of the conversation id or null.
showChatHeader
boolean

optional
Used to control if the Chat Header is displayed in the UI. Defaults to true.
showFeedHeader
boolean

optional
Controls if the feed header containing the toggle to enable desktop notifications is shown. Defaults to true.
thirdparties

optional
TalkJS leverages iframes behind the scenes and therefore not all services that you use in your app will work out of the box. This option adds support for a number of services to help you use them. Let us know if you're missing any.
translateConversations
boolean | string[] | ConversationBuilder[]

optional
TalkJS can translate conversations to the current user's locale using Google Translate. This option specifies which conversations should be translated in this UI. You can pass a boolean to enable/disable translation for all conversations, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the enterprise plan. Make sure you add your Google API key in the dashboard.
useBrowserHistory
boolean

optional
Controls whether the user navigating between conversation should count as steps in the browser history. Defaults to true, which means that if the user clicks the browser's back button, they go back to the previous conversation (if any).

Returns

Inbox

createPopup

session.createPopup(conversation, options): Popup

Creates a Popup UI

The Popup is a beautiful, well positioned box containing a conversation. It shows a single conversation, without a means to switch between conversations. In order to have a popup on each site you need to call createPopup on any page you want to show a popup with the conversation.

Parameters

conversation

The conversation to show on the UI.

options

optional

interface PopupOptions

chatSubtitleMode
"subject" | "participants" | null

optional
Controls what text appears in the chat subtitle, right below the chat title. No subtitle is displayed when the conversation has no subject set or when set to null. Defaults to "subject". (also see chatTitleMode and InboxOptions.feedConversationTitleMode)
chatTitleMode
"subject" | "participants"

optional
Controls what text appears in the chat title, in the header above the messages. Defaults to "participants". (also see chatSubtitleMode and InboxOptions.feedConversationTitleMode)
dir
"rtl" | "ltr"

optional
Controls the text direction (for supporting right-to-left languages such as Arabic and Hebrew). TalkJS tries to determine the appropriate text direction from the parent page, but if that does not work or you want to explicitly control it, you can override it here. Defaults to "rtl".
keepOpen
boolean

optional
If enabled, the Popup will reopen every time the user navigates to another page. This way, a conversation can continue while the user browses around. Set to false to disable this behavior. Defaults to true.
launcher
"close-only" | "always" | "never"

optional
Specifies whether to show a round launcher and/or close button beneath the popup in the right bottom corner of the page.

"close-only": show a close button beneath the popup, but don't show a launch button

"always": show a launch button when the popup is closed, show a close button when it is visible

"never": never show a launcher

Note: if you choose "never" you may want to override the positioning of the popup as well. Just tune the __talkjs_popup class in your CSS.

Ignored on mobile, where the popup fills the entire screen so the value is effectively "never".

Defaults to "close-only".

messageField

optional
Settings that affect the behavior of the message field
messageFilter

optional
Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes. See MessagePredicate for all available options. You can also modify the filter on the fly using Popup.setMessageFilter.
messageSuggestion
string

optional
Sets the message input box to the given text. You can use this to suggest a certain initial message to be sent. The user can still edit it before hitting "send".
showChatHeader
boolean

optional
Used to control if the Chat Header is displayed in the UI. Defaults to true.
showCloseInHeader
boolean | "auto"

optional
Whether to show the "x" icon in the popup header to close the popup. "auto", which is the default value means true on mobile and to false on desktop.
thirdparties

optional
TalkJS leverages iframes behind the scenes and therefore not all services that you use in your app will work out of the box. This option adds support for a number of services to help you use them. Let us know if you're missing any.
translateConversations
boolean | string[] | ConversationBuilder[]

optional
TalkJS can translate conversations to the current user's locale using Google Translate. This option specifies which conversations should be translated in this UI. You can pass a boolean to enable/disable translation for all conversations, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the enterprise plan. Make sure you add your Google API key in the dashboard.

Returns

Popup

destroy

session.destroy()

Disconnects all websockets, removes all UIs, and invalidates this session. You cannot use any objects that were created in this session after you destroy it. If you want to use TalkJS after having called destroy() you must instantiate a new Talk.Session instance.

Parameters

None.

Returns

void

getOrCreateConversation

session.getOrCreateConversation(conversationId): ConversationBuilder

A method used to either fetch or create a conversation.

Returns a ConversationBuilder object that encapsulates a conversation between me (given in the constructor) and zero or more other participants. Use ConversationBuilder.setParticipant and ConversationBuilder.setAttributes on the returned object to further set up your conversation.

Parameters

conversationId
string

A unique identifier for this conversation, such as a channel name or topic ID. Any user with access to this ID can join this conversation. Read about how to choose a good conversation ID for your use case. If you want to make a simple one-on-one conversation, consider using oneOnOneId to generate one.

Returns

ConversationBuilder

getOrStartConversation

This method has 2 overloads:
session.getOrStartConversation(other, options): Conversation

Deprecated. This method will keep being supported, but for new projects, we recommend that you use getOrCreateConversation. Returns a Conversation object that encapsulates a conversation between me (given in the constructor) and other.

Parameters

other

A User object that identifies the person to converse with. The user is uniquely identified by their id; all other fields (name, photo etc) are overwritten in the TalkJS database each time they change.

options
GetOrStartOptionsA

optional

Options used for getOrStartConversation

Returns

Conversation
session.getOrStartConversation(conversationId, options): Conversation

Deprecated. This method will keep being supported, but for new projects, we recommend that you use getOrCreateConversation. Returns a Conversation object that encapsulates a conversation between me (given in the constructor) and zero or more other participants.

Parameters

conversationId
string

A unique identifier for this conversation. Any user with access to this ID can join this conversation.

options
GetOrStartOptionsB

optional

Options used for getOrStartConversation

Returns

Conversation

hasValidCredentials

session.hasValidCredentials(): Promise<boolean>

Verifies whether the appId is valid.

Returns a Promise of a boolean, never rejects.

Parameters

None.

Returns

Promise<boolean>

off

session.off(eventType, handler)

Used to stop listening to specific TalkJS session events

Call this with the same eventType and handler to stop receiving events.

Related methods: Session.on

Parameters

eventType
"message"
handler
(message: Message) => void

Returns

void

on

session.on(eventType, handler)

Used to listen to TalkJS session events

A "message" event is fired every time a message is sent or received by the current user (even if no TalkJS UI is visible). Your handler function is passed a Message object with some information about each message and its conversation.

For an example, see

Related method: Session.off

Parameters

eventType
"message"
handler
(message: Message) => void

Returns

void

registerDevice

session.registerDevice({ platform, pushRegistrationId }): Promise<void>

Registers mobile device, one user can be connected to one mobile device.

Related method: Session.unregisterDevice

Parameters

{ platform, pushRegistrationId }
{     platform: "ios" | "android"     pushRegistrationId: string }

Returns

Promise<void>

setDesktopNotificationEnabled

session.setDesktopNotificationEnabled(isEnabled, { alertOnFailure }): Promise<void>

Sets desktop notification on or off.

Has the same effect as toggling the "Desktop notification" toggle in the TalkJS Inbox UI. Use this function to replicate that toggle elsewhere in your UI if you're using TalkJS in a mode that doesn't show this toggle.

Parameters

isEnabled
boolean

Whether notifications should be enabled.

{ alertOnFailure }
{     alertOnFailure?: boolean }

optional

Returns

Promise<void>

a promise that'll resolve if the change succeeds, but rejects if anything goes wrong. If anything goes wrong, the promise will be rejected with a Talk.Error, which has a code property. Possible values for it are:

- Talk.Error.Code.NOTIFICATIONS_PERMISSION_DENIED: The browser or the user didn't grant you permission to send notifications.

- Talk.Error.Code.NOTIFICATIONS_NOT_SUPPORTED: The browser doesn't support desktop notifications.


syncThemeForLocalDev

session.syncThemeForLocalDev(path)

Used to configure TalkJS to use a theme hosted on the same location as your application for development.

Tells TalkJS to use a theme hosted on the same location as your application (e.g. localhost:8000/). e.g. Call talkSession.syncThemeForLocalDev("/assets/css/talkjs-theme.css") just before you call createInbox or createChatbox. TalkJS will then use the specified file instead of using a theme created in the dashboard.

Parameters

path
string

The path to the theme's CSS file

Returns

void

unregisterDevice

session.unregisterDevice(): Promise<void>

Unregisters mobile device, one user can be connected to one mobile device.

Related method: Session.registerDevice

Parameters

None.

Returns

Promise<void>

interface Unreads

This object can notify you when the amount of unread conversations changes. You can't instantiate it - instead, get an instance via Session.unreads.

Methods

off

Call this with the same eventType and handler that you used for on to stop receiving events.

on

A "change" event is fired on startup right after TalkJS loads, as well as every time the amount of unread conversations changed. The handler is invoked with an array of objects with limited information about each conversation, see UnreadConversation.

Method Details

off

unreads.off(eventType, handler)

Call this with the same eventType and handler that you used for on to stop receiving events.

Related methods: on

Parameters

eventType
"change"
handler
(messages: UnreadConversation[]) => void

Returns

void

on

unreads.on(eventType, handler)

A "change" event is fired on startup right after TalkJS loads, as well as every time the amount of unread conversations changed. The handler is invoked with an array of objects with limited information about each conversation, see UnreadConversation.

Related methods: off

Parameters

eventType
"change"
handler
(messages: UnreadConversation[]) => void

Returns

void

interface UnreadConversation

Used as part of Unreads.on.

Properties

lastMessage
Contains the last Message for an unread conversation.

interface Message

attachment
{     url: string     size: number } | null
Only given if the message's type equals "media". An object with the URL and filesize (in bytes) of the given file.
body
string
Contains the message's content
conversation
Contains the ConversationData that the message belongs to.
custom
Custom metadata that is stored with the convesation
isByMe
boolean
'true' if the message was sent by the current user.
location
[number, number] | null
Only given if the message's type equals "location". An array of two numbers which represent the longitude and latitude of this location, respectively. Only given if this message is a shared location. Example:
[51.481083, -3.178306]
origin
string
Determines how this message was sent: respectively, Via a web browser (or mobile Webview), via the REST API, via reply-to-email, or using the import API.
read
boolean
'true' if the message has been read, 'false' has not been seen yet
sender
UserData | null
The User that sent the message
senderId
string | null
The senderID (userID) for the person that sent the message
timestamp
number
The timestamp for the when the message was sent
type
"media" | "text" | "location"
Specifies if if the message is media (file), text or a shared location

interface DesktopNotificationToggledEvent

This event is triggered when desktop notifications are toggled.

Properties

isEnabled
boolean
Boolean indicating if desktop Notifications are enabled or not

interface Message

A TalkJS message, used as part of Session.on

Properties

attachment
{     url: string     size: number } | null
Only given if the message's type equals "media". An object with the URL and filesize (in bytes) of the given file.
body
string
Contains the message's content
conversation
Contains the ConversationData that the message belongs to.

interface ConversationData

custom
Contains custom metadata for the conversation if it was set using ConversationBuilder.custom.
id
string
The ID of the conversation
photoUrl
string | null
Contains the URL of a photo was set using ConversationBuilder.subject.
subject
string | null
Contains the conversation subject if it was set using ConversationBuilder.subject.
topicId
string | null

Deprecated. Please use ConversationBuilder.subject instead.

welcomeMessages
Array<string> | null
One or more welcome messages that will display to the user as a SystemMessage
custom
Custom metadata that is stored with the convesation

interface CustomData

[key]
string

optional
Any number of key/value pairs of your choosing to be stored along with the associated resource. You can use custom data for all kinds of purposes, such as customizing a user's email notification text, transmitting contextual user data, or making email login tokens. Both the key and the value must be strings; arbitrarily deeply nested JSON is not supported. Example:
{"country":"nl", "itemId": "720"}
isByMe
boolean
'true' if the message was sent by the current user.
location
[number, number] | null
Only given if the message's type equals "location". An array of two numbers which represent the longitude and latitude of this location, respectively. Only given if this message is a shared location. Example:
[51.481083, -3.178306]
origin
string
Determines how this message was sent: respectively, Via a web browser (or mobile Webview), via the REST API, via reply-to-email, or using the import API.
read
boolean
'true' if the message has been read, 'false' has not been seen yet
sender
UserData | null
The User that sent the message
senderId
string | null
The senderID (userID) for the person that sent the message
timestamp
number
The timestamp for the when the message was sent
type
"media" | "text" | "location"
Specifies if if the message is media (file), text or a shared location