Session

class Session

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

Method Overview

Constructor

Creates a TalkJS Session.

clearPushRegistrations

Unregisters all the mobile devices for the user.

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.

getChatboxes

Returns a list of all active Chatbox objects linked to this session.

getInboxes

Returns a list of all active Inbox objects linked to this session.

getOrCreateConversation

A method used to either fetch or create a conversation.

getPopups

Returns a list of all active Popup objects linked to this session.

hasValidCredentials

Verifies whether the appId is valid.

onDesktopNotificationClicked

Listen for when a user clicks a desktop notification.

onMessage

Triggered when a message is sent in a conversation the current user is in.

setDesktopNotification­Enabled

Sets desktop notification on or off.

setPushRegistration

Registers a single mobile device, as one user can be connected to multiple mobile devices.

syncThemeForLocalDev

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

unsetPushRegistration

Unregisters a single mobile device, as one user can be connected to multiple mobile devices.

getOrStartConversation Deprecated

off Deprecated

Used to stop listening to specific TalkJS session events.

on Deprecated

Listens for an event

registerDevice Deprecated

unregisterDevice Deprecated

Properties

appId
: string

Your TalkJS AppId that can be found your TalkJS dashboard.

me
: User

The TalkJS User associated with the current user in your application.

unreads
: Unreads

Holds information about unread conversations. Lets your app be notified when the active user receives a new message.

Constructor

new Session(options)
Creates a TalkJS Session.

Parameters

options
: SessionOptions
interface SessionOptions
appId
: string

Your app's unique TalkJS id. Get it from the dashboard.

me
: User

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, unless the user has been created with the alternate constructor.

signature (optional)
: string

If you use Identity verification make sure you generate and use a signature.

clearPushRegistrations

session.clearPushRegistrations(): Promise<void>
Unregisters all the mobile devices for the user.

Related methods: setPushRegistration unsetPushRegistration

Note that you must ensure that the user exists in the TalkJS database before you call this method. The simplest way to do that is to call it after you mount a chatbox, inbox or popup.

Parameters

None.

Returns

Promise<void>

createChatbox

session.createChatbox(options): Chatbox
Creates a Chatbox UI.

The Chatbox is a slimmer version of the Inbox. It shows a single conversation, without means to switch between conversations. In order to select a conversation inside a Chatbox you need to call Chatbox​.select.

Example:

const chatbox = session.createChatbox();
chatbox.select(conversation);

You typically want to call Chatbox​.mount after creating the Chatbox to make it visible on your app.

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

Note: A deprecated two-parameter form of this method, createChatbox(selectedConversation, options), also exists. This form will keep being supported but we recommend not using it new codebases. Instead, call Chatbox​.select immediately after mount.

Parameters

options (optional)
: ChatboxOptions

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

interface ChatboxOptions
captureKeyboardEvents (optional)
: boolean

Enables capturing Chatbox​.onKeyup events.

Note: Setting this to true also disables any non-standard keyboard shortcuts in TalkJS.

At the time of writing, the only such shortcut is that when captureKeyboardEvents is disabled, TalkJS will auto-focus the message field if the user starts typing but no input field is focused.

dir (optional)
: "rtl" | "ltr"

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)
: MessageFieldOptions

Settings that affect the behavior of the message field

messageFilter (optional)
: MessagePredicate

Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes.

*Note*: Messages are only filtered in the message list. The inbox UI's conversation feed will always show the last message sent to the conversation, regardless of the message filter set.

See MessagePredicate for all available options.

You can also modify the filter on the fly using Chatbox​.setMessageFilter.

presence (optional)
: UserPresence

Sets metadata for the current session.

- visible manually sets the information about the visibility of TalkJS. This is useful when TalkJS is hidden with CSS. TalkJS will assume that UIs marked visible: false cannot be seen, and thus messages arriving on this UI will not be marked as read until you set visible to true again.

- custom is an additional parameter to store the custom fields, that you may want to use in the REST API call.

showChatHeader (optional)
: boolean

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

showTranslationToggle (optional)
: boolean | "auto"

Set this to true to show a translation toggle in all conversations. Set this to "auto" to show a translation toggle in conversations where there are participants with different locales. This setting defaults to false, meaning that no toggles will be shown. In order to use this, you must be on the Growth plan, and set a Google Translate API key in the dashboard.

theme (optional)
: string

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor.

If you omit this field, the UI uses the theme that is selected in the current user's role.

thirdparties (optional)
: ThirdPartyOptions

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 (optional)
: boolean | "auto" | string[] | ConversationBuilder[]

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, "auto" to enable translation on conversations where users have different locales, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the Growth plan and above. Make sure you add your Google Translate API key in the dashboard.

Deprecated chatSubtitleMode (optional)
: "subject" | "participants" | null

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)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated chatTitleMode (optional)
: "subject" | "participants"

Controls what text appears in the chat title, in the header above the messages. Defaults to "participants".

(also see chatSubtitleMode and InboxOptions​.feedConversationTitleMode)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated messageSuggestion (optional)
: string

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

Deprecated.

We recommend using MessageField​.setText before mounting the chatbox to precisely control when message suggestions are shown.

Returns

Chatbox

createInbox

session.createInbox(options): Inbox
Creates an Inbox UI

The Inbox is TalkJS's most versatile component. It combines a Chatbox with a panel showing a a list of conversations where the user is a participant. After creating an Inbox, you need to Inbox​.mount it to make it visible in your app.

Call createInbox on the messaging page of your app.

Parameters

options (optional)
: InboxOptions

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

interface InboxOptions
captureKeyboardEvents (optional)
: boolean

Enables capturing Chatbox​.onKeyup events.

Note: Setting this to true also disables any non-standard keyboard shortcuts in TalkJS.

At the time of writing, the only such shortcut is that when captureKeyboardEvents is disabled, TalkJS will auto-focus the message field if the user starts typing but no input field is focused.

dir (optional)
: "rtl" | "ltr"

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

feedFilter (optional)
: ConversationPredicate

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)
: MessageFieldOptions

Settings that affect the behavior of the message field

messageFilter (optional)
: MessagePredicate

Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes.

*Note*: Messages are only filtered in the message list. The inbox UI's conversation feed will always show the last message sent to the conversation, regardless of the message filter set.

See MessagePredicate for all available options.

You can also modify the filter on the fly using Inbox​.setMessageFilter.

presence (optional)
: UserPresence

Sets metadata for the current session.

- visible manually sets the information about the visibility of TalkJS. This is useful when TalkJS is hidden with CSS. TalkJS will assume that UIs marked visible: false cannot be seen, and thus messages arriving on this UI will not be marked as read until you set visible to true again.

- custom is an additional parameter to store the custom fields, that you may want to use in the REST API call.

selected (optional)
: Conversation | ConversationBuilder | string | null

Makes the inbox start up with the given Conversation. Can be passed a value of the type ConversationBuilder (returned by getOrCreateConversation) or the string value of the conversation id. Conversation can be deselected on startup by passing a null value. Passing undefined means that the last conversation (or "no chats yet page") will be displayed.

showChatHeader (optional)
: boolean

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

showFeedHeader (optional)
: boolean

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

showMobileBackButton (optional)
: boolean

Whether to show a "Back" button at the top of the chat screen on mobile devices.

showTranslationToggle (optional)
: boolean | "auto"

Set this to true to show a translation toggle in all conversations. Set this to "auto" to show a translation toggle in conversations where there are participants with different locales. This setting defaults to false, meaning that no toggles will be shown. In order to use this, you must be on the Growth plan, and set a Google Translate API key in the dashboard.

theme (optional)
: string

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor.

If you omit this field, the UI uses the theme that is selected in the current user's role.

thirdparties (optional)
: ThirdPartyOptions

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 (optional)
: boolean | "auto" | string[] | ConversationBuilder[]

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, "auto" to enable translation on conversations where users have different locales, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the Growth plan and above. Make sure you add your Google Translate API key in the dashboard.

useBrowserHistory (optional)
: boolean

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

Deprecated chatSubtitleMode (optional)
: "subject" | "participants" | null

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)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated chatTitleMode (optional)
: "subject" | "participants"

Controls what text appears in the chat title, in the header above the messages. Defaults to "participants".

(also see chatSubtitleMode and feedConversationTitleMode)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated feedConversationTitleMode (optional)
: "participants" | "subject" | "auto"

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)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ConversationListItem component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated messageSuggestion (optional)
: string

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

Deprecated.

We recommend using MessageField​.setText before mounting the chatbox to precisely control when message suggestions are shown.

Returns

Inbox

createPopup

session.createPopup(options): Popup
Creates a Popup UI.

The Popup is a positioned box containing a conversation. It shows a single conversation, without means to switch between conversations. In order to select a conversation inside a Popup you need to call the Popup​.select.

Example:

const popup = session.createPopup();
popup.select(conversation);

You typically want to call Popup​.mount after creating the popup to make it visible on your app.

Call createPopup on any page you want to show a popup of a single conversation.

Note: A deprecated two-parameter form of this method, createChatbox(selectedConversation, options), also exists. This form will keep being supported but we recommend not using it new codebases. Instead, call Chatbox​.select immediately after mount. 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

options (optional)
: PopupOptions

Optional, Use these to finetune the behavior of the Popup.

interface PopupOptions
captureKeyboardEvents (optional)
: boolean

Enables capturing Chatbox​.onKeyup events.

Note: Setting this to true also disables any non-standard keyboard shortcuts in TalkJS.

At the time of writing, the only such shortcut is that when captureKeyboardEvents is disabled, TalkJS will auto-focus the message field if the user starts typing but no input field is focused.

dir (optional)
: "rtl" | "ltr"

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 (optional)
: boolean

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

launcher (optional)
: "close-only" | "always" | "never"

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

messageField (optional)
: MessageFieldOptions

Settings that affect the behavior of the message field

messageFilter (optional)
: MessagePredicate

Used to control which messages are shown in the message list, depending on a type, origin or custom message attributes.

*Note*: Messages are only filtered in the message list. The inbox UI's conversation feed will always show the last message sent to the conversation, regardless of the message filter set.

See MessagePredicate for all available options.

You can also modify the filter on the fly using Popup​.setMessageFilter.

presence (optional)
: UserPresence

Sets metadata for the current session.

- visible manually sets the information about the visibility of TalkJS. This is useful when TalkJS is hidden with CSS. TalkJS will assume that UIs marked visible: false cannot be seen, and thus messages arriving on this UI will not be marked as read until you set visible to true again.

- custom is an additional parameter to store the custom fields, that you may want to use in the REST API call.

showChatHeader (optional)
: boolean

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

showCloseInHeader (optional)
: boolean | "auto"

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.

showTranslationToggle (optional)
: boolean | "auto"

Set this to true to show a translation toggle in all conversations. Set this to "auto" to show a translation toggle in conversations where there are participants with different locales. This setting defaults to false, meaning that no toggles will be shown. In order to use this, you must be on the Growth plan, and set a Google Translate API key in the dashboard.

theme (optional)
: string

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor.

If you omit this field, the UI uses the theme that is selected in the current user's role.

thirdparties (optional)
: ThirdPartyOptions

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 (optional)
: boolean | "auto" | string[] | ConversationBuilder[]

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, "auto" to enable translation on conversations where users have different locales, or you can pass an array of ConversationBuilders or conversation Ids to be translated. This feature is only available on the Growth plan and above. Make sure you add your Google Translate API key in the dashboard.

Deprecated chatSubtitleMode (optional)
: "subject" | "participants" | null

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)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated chatTitleMode (optional)
: "subject" | "participants"

Controls what text appears in the chat title, in the header above the messages. Defaults to "participants".

(also see chatSubtitleMode and InboxOptions​.feedConversationTitleMode)

Deprecated.

This field only has effect if you use a Legacy Theme, or an older custom theme which does not have a ChatHeader component. If you do not, edit the ChatHeader component in the theme editor instead.

Deprecated messageSuggestion (optional)
: string

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

Deprecated.

We recommend using MessageField​.setText before mounting the chatbox to precisely control when message suggestions are shown.

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

getChatboxes

session.getChatboxes(): Chatbox[]
Returns a list of all active Chatbox objects linked to this session.

Only includes chatboxes that are still mounted in the DOM. So if you call createChatbox() but later remove its container element (or an ancestor of the container), then the Chatbox object will have been made invalid and is therefore not included in the results.

Parameters

None.

Returns

Chatbox[]

getInboxes

session.getInboxes(): Inbox[]
Returns a list of all active Inbox objects linked to this session.

Only includes inboxes that are still mounted in the DOM. So if you call createInbox() but later remove its container element (or an ancestor of the container), then the Inbox object will have been made invalid and is therefore not included in the results.

Parameters

None.

Returns

Inbox[]

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

getPopups

session.getPopups(): Popup[]
Returns a list of all active Popup objects linked to this session.

Includes popups actively created using createPopup, and also popups created on page load, if PopupOptions​.keepOpen was set to true on an earlier page.

Only includes popups that are still mounted in the DOM. So if you call createPopup() but later remove its container element (or an ancestor of the container), then the Popup object will have been made invalid and is therefore not included in the results.

Parameters

None.

Returns

Popup[]

hasValidCredentials

session.hasValidCredentials(): Promise<boolean>
Verifies whether the appId is valid.

Returns a Promise of a boolean, never rejects.

Parameters

None.

Returns

Promise<boolean>

onDesktopNotificationClicked

session.onDesktopNotificationClicked(handler): Subscription
Listen for when a user clicks a desktop notification.

A "desktopNotificationClicked" event is fired every time a user clicks on a desktop notification generated by TalkJS.

When a user clicks on a notification, these things will happen:

1. The browser tab will be selected (note, this works in most browsers but cannot be guaranteed);

2. If you provided one or more "desktopNotificationClicked" handlers, they will be invoked in order;

3. If you did not, then the currently active inbox (if any) will jump to the conversation corresponding to the notification.

See also setDesktopNotification­Enabled

Parameters

handler
: (message: Message) => void

Returns

Subscription

onMessage

session.onMessage(handler): Subscription
Triggered when a message is sent in a conversation the current user is in.

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.

Note that this event does not get triggered for conversations where the current user is a guest. It only applies to users who were added as participants.

Parameters

handler
: (message: Message) => void

Returns

Subscription

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.

When desktop notifications are enabled for the first time, the browser will show a prompt to ask the user for permission. The call will only succeed if the user accepts it.

We recommend only calling this function in response to user action, so users know that they can expect a permission prompt. This significantly increases the percentage of users that click "Allow".

Notably, we strongly recommend that you do not call this function immediately when the page loads, because many browsers auto block notifications when permission is requested on page load. This is likely a measure to prevent overly aggressive news sites from being able to spam past visitors.

Parameters

isEnabled
: boolean

Whether notifications should be enabled.

{ alertOnFailure } (optional)
: { alertOnFailure?: boolean }

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 TalkError, which has a code property. Possible values for it are:

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

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

setPushRegistration

session.setPushRegistration({
provider: "fcm" | "apns";
pushRegistrationId: string;
}): Promise<void>
Registers a single mobile device, as one user can be connected to multiple mobile devices.

Related methods: unsetPushRegistration clearPushRegistrations

Note that you must ensure that the user exists in the TalkJS database before you call this method. The simplest way to do that is to call it after you mount a chatbox, inbox or popup.

Parameters

{ provider, pushRegistrationId, }
: { provider: "fcm" | "apns" pushRegistrationId: string }

Returns

Promise<void>

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

unsetPushRegistration

session.unsetPushRegistration({
provider: "fcm" | "apns";
pushRegistrationId: string;
}): Promise<void>
Unregisters a single mobile device, as one user can be connected to multiple mobile devices.

Related methods: setPushRegistration clearPushRegistrations

Note that you must ensure that the user exists in the TalkJS database before you call this method. The simplest way to do that is to call it after you mount a chatbox, inbox or popup.

Parameters

{ provider, pushRegistrationId, }
: { provider: "fcm" | "apns" pushRegistrationId: string }

Returns

Promise<void>

Deprecated Methods

The following methods remain supported for backward compatibility reasons. In new projects, we recommend that you use the suggested alternatives instead.

getOrStartConversation Deprecated

off Deprecated

Used to stop listening to specific TalkJS session events.

on Deprecated

Listens for an event

registerDevice Deprecated

unregisterDevice Deprecated

Deprecated 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
: User

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 (optional)
: GetOrStartOptionsA

Options used for getOrStartConversation

interface GetOrStartOptionsA
custom (optional)
: { [name: string]: string }

Additional parameter to store the custom fields, that you want to use in the email template. E.g. custom.specialToken

photoUrl (optional)
: string

Photo to be used for this conversation in the TalkJS UI.

subject (optional)
: string

Only used if topicId is given: a human-readable subject of the conversation. Supports formatted links in a Markdown-style syntax, e.g. Beautiful <https://yoursite.com/booking/18644|home by the sea>!. URLs and email addresses are made clickable, and emojis made to work cross-platform.

topicId (optional)
: string
welcomeMessages (optional)
: string[]

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 (optional)
: GetOrStartOptionsB

Options used for getOrStartConversation

interface GetOrStartOptionsB
custom (optional)
: { [name: string]: string }

Additional parameter to store the custom fields, that you want to use in the email template. E.g. custom.specialToken

participants
: Array<User>
photoUrl (optional)
: string

Photo to be used for this conversation in the TalkJS UI.

subject (optional)
: string

Only used if topicId is given: a human-readable subject of the conversation. Supports formatted links in a Markdown-style syntax, e.g. Beautiful <https://yoursite.com/booking/18644|home by the sea>!. URLs and email addresses are made clickable, and emojis made to work cross-platform.

Returns

Conversation

Deprecated off

This method has 2 overloads
session.off("message", handler)
Used to stop listening to specific TalkJS session events.

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

Deprecated. Please use the Subscription​.unsubscribe method on the object returned by onMessage instead.

Parameters

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

Returns

void
session.off("desktopNotificationClicked", handler)
Used to stop listening to specific TalkJS session events.

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

Deprecated. Please use the Subscription​.unsubscribe method on the object returned by onDesktopNotificationClicked instead.

Parameters

eventType
: "desktopNotificationClicked"
handler
: (event: DesktopNotificationClickedEvent) => void

Returns

void

Deprecated on

This method has 2 overloads
session.on("message", handler)
Listens for an event

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

Note that this event does not get triggered for conversations where the current user is a guest. It only applies to users who were added as participants.

Related method: off

Deprecated. Please use onMessage instead.

Parameters

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

Returns

void
session.on("desktopNotificationClicked", handler)
Listens for an event

A "desktopNotificationClicked" event is fired every time a user clicks on a desktop notification generated by TalkJS.

When a user clicks on a notification, these things will happen:

1. The browser tab will be selected (note, this works in most browsers but cannot be guaranteed);

2. If you provided one or more "desktopNotificationClicked" handlers, they will be invoked in order;

3. If you did not, then the currently active inbox (if any) will jump to the conversation corresponding to the notification.

See also setDesktopNotification­Enabled and off

Deprecated. Please use onDesktopNotificationClicked instead.

Parameters

eventType
: "desktopNotificationClicked"
handler
: (event: DesktopNotificationClickedEvent) => void

Returns

void

Deprecated registerDevice

session.registerDevice({
platform: "ios" | "android";
pushRegistrationId: string;
}): Promise<void>

Related method: Session.unregisterDevice

Note that you must ensure that the user exists in the TalkJS database before you call this method. The simplest way to do that is to call it after you mount a chatbox, inbox or popup.

Deprecated. This method will keep being supported, but for new projects, we recommend that you use setPushRegistration. Registers mobile device, one user can be connected to one mobile device.

Parameters

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

Returns

Promise<void>

Deprecated unregisterDevice

session.unregisterDevice(): Promise<void>

Related method: Session.registerDevice

Deprecated. This method will keep being supported, but for new projects, we recommend that you use unsetPushRegistration or clearPushRegistrations. Unregisters mobile device, one user can be connected to one mobile device.

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.

Method Overview

onChange

Triggered when the list of unread conversations changes.

off Deprecated

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

on Deprecated

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.

onChange

unreads.onChange(handler): Subscription
Triggered when the list of unread conversations changes.

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.

Note that conversations where the user is a guest do not keep track of unread messages. This is only done for users who are added as participants.

Parameters

handler
: (messages: UnreadConversation[]) => void

Returns

Subscription

Deprecated Methods

The following methods remain supported for backward compatibility reasons. In new projects, we recommend that you use the suggested alternatives instead.

off Deprecated

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

on Deprecated

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.

Deprecated off

unreads.off("change", handler)
Call this with the same eventType and handler that you used for on to stop receiving events.

Related methods: on

Deprecated. Please use the Subscription​.unsubscribe method on the object returned by onChange instead.

Parameters

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

Returns

void

Deprecated on

unreads.on("change", 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.

Note that conversations where the user is a guest do not keep track of unread messages. This is only done for users who are added as participants.

Related methods: off

Deprecated. Please use onChange instead.

Parameters

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

Returns

void

interface UnreadConversation

Used as part of Unreads​.on.

Properties

lastMessage
: Message

Contains the last Message for an unread conversation.

interface Message

A TalkJS message, used as part of Session​.onMessage

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
: ConversationData

Contains the ConversationData that the message belongs to.

custom
: CustomData

Custom metadata that is stored with the conversation

id
: string

The message's ID.

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

UNIX timestamp specifying when the message was sent (UTC, in milliseconds)

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

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
: ConversationData

Contains the ConversationData that the message belongs to.

interface ConversationData
custom
: CustomData

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.

welcomeMessages
: Array<string> | null

One or more welcome messages that will display to the user as a SystemMessage

Deprecated topicId
: string | null

Deprecated.

Please use ConversationBuilder​.subject instead.

custom
: CustomData

Custom metadata that is stored with the conversation

interface CustomData

Used to store additional metadata on users, conversations and messages

[key] (optional)
: string

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"}

id
: string

The message's ID.

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

UNIX timestamp specifying when the message was sent (UTC, in milliseconds)

type
: "media" | "text" | "location"

Specifies if if the message is media (file), text or a shared location