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.

conversation

Get a reference to a conversation, for use with the Realtime API

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.

onBrowserPermissionDenied

Triggered when the user tried to do an action that requires explicit browser permission, but this permission was denied.

onBrowserPermissionNeeded

Triggered when a browser permission prompt is about to be shown.

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.

unsetPushRegistration

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

user

Get a reference to a user, for use with the Realtime API

off Deprecated

Used to stop listening to specific TalkJS session events.

on Deprecated

Listens for an event

registerDevice Deprecated
syncThemeForLocalDev Deprecated

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

unregisterDevice Deprecated

Properties

appId
: string

Your TalkJS AppId that can be found on the "Settings" page of your TalkJS dashboard.

currentUser
: UserRef

A reference to the current user

isAlive
: boolean

Whether the session is active and in a valid state.

When false, calling methods on this Session instance will throw errors.

This field is false when destroy has been called in the past. Once a session has been destroyed, you cannot revive it. Instead, create a new session.

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 "Settings" page of your 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.

token (optional)
: string

A token to authenticate the session with.

See the how-to guide on generating authentication tokens, and many examples in different programming languages.

See the reference documentation for full details on the technical requirements for the JWT.

tokenFetcher (optional)
: () => Promise<string>

A function that fetches and returns a new authentication token from your server. TalkJS calls this function whenever the current token is about to expire. This callback is designed to work with any backend setup.

See the how-to guide on refreshable authentication tokens, and many examples in different programming languages.

Deprecated signature (optional)
: string

Legacy alternative to JWT authentication. A HMAC-SHA256 hash of the current user ID, signed with your TalkJS secret key.

See the documentation for examples of how to generate a signature in different programming languages.

Deprecated. This will keep being supported, but for new projects, use token instead. JWT authentication is recommended because signatures never expire, meaning there is no way to revoke access.

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.

Returns

Promise<void>

conversation

session.conversation(id): ConversationRef

Get a reference to a conversation, for use with the Realtime API

Parameters

id
: string

The ID of the conversation that you want to reference

Returns

ConversationRef

A ConversationRef for the conversation with that ID

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:

1const chatbox = session.createChatbox();
2chatbox.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.

customEmojis (optional)
: { [name: string]: CustomEmojiDefinition }

Allows users to send and receive custom emojis.

This adds a set of custom emoji images to the emoji picker, the emoji autocompleter, and emoji reactions.

Every emoji name *must* start and end with a colon, for example :lol:.

Make sure you always specify a consistent, backward-compatible set of custom emojis. If an existing message contains a custom emoji that is not specified in customEmojis here, then the emoji cannot be displayed and the textual name will be displayed instead (including colons).

If you want to allow an emoji to be displayed if it's used in existing data, but not let users select it in new messages/reactions, set the hidden option to true for that emoji.

Example

1{
2 ":lol:": { url: "https://example.com/images/emoji-lol.svg" },
3 ":roomba-cat:": { url: "https://example.com/images/roomba-cat.gif" },
4 ":alert:": { url: "https://example.com/images/alert.gif", hidden: true },
5}

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 on the "Settings" page of the dashboard.

theme (optional)
: string | ThemeOptions

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor. If you don't pass a theme name, we'll first check for a theme set in the user's role, and then fall back to using the default theme.

You can either pass the name of the theme you'd like to use, or a ThemeOptions object, which you can use to pass variables to your theme.

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 or turn off 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 on the "Settings" page of 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. In order to select a conversation inside an Inbox you need to call Inbox​.select.

Example:

1const inbox = session.createInbox();
2inbox.select(conversation);

You typically want to call Inbox​.mount after creating the Inbox to make it visible on 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.

customEmojis (optional)
: { [name: string]: CustomEmojiDefinition }

Allows users to send and receive custom emojis.

This adds a set of custom emoji images to the emoji picker, the emoji autocompleter, and emoji reactions.

Every emoji name *must* start and end with a colon, for example :lol:.

Make sure you always specify a consistent, backward-compatible set of custom emojis. If an existing message contains a custom emoji that is not specified in customEmojis here, then the emoji cannot be displayed and the textual name will be displayed instead (including colons).

If you want to allow an emoji to be displayed if it's used in existing data, but not let users select it in new messages/reactions, set the hidden option to true for that emoji.

Example

1{
2 ":lol:": { url: "https://example.com/images/emoji-lol.svg" },
3 ":roomba-cat:": { url: "https://example.com/images/roomba-cat.gif" },
4 ":alert:": { url: "https://example.com/images/alert.gif", hidden: true },
5}

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.

The feedFilter can be either of the following: - a single ConversationPredicate object that filters based on all the fields of the predicate - an array that gives you all the conversations that satisfy at least one of the ConversationPredicates

When filtering conversations with an array, the first element must be the string "any", and the second element a list of ConversationPredicate objects.

For example, to match all the conversations to which you have read access, or whose custom "accountId" field has the "my_account" value, use the following:

1["any", [{"access": ["==", "Read"]}, {"custom": {"accountId": ["==", "my_account"]}}]]

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.

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 on the "Settings" page of the dashboard.

theme (optional)
: string | ThemeOptions

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor. If you don't pass a theme name, we'll first check for a theme set in the user's role, and then fall back to using the default theme.

You can either pass the name of the theme you'd like to use, or a ThemeOptions object, which you can use to pass variables to your theme.

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 or turn off 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 on the "Settings" page of 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.

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

Deprecated. Please use Inbox.select instead.

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:

1const popup = session.createPopup();
2popup.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.

customEmojis (optional)
: { [name: string]: CustomEmojiDefinition }

Allows users to send and receive custom emojis.

This adds a set of custom emoji images to the emoji picker, the emoji autocompleter, and emoji reactions.

Every emoji name *must* start and end with a colon, for example :lol:.

Make sure you always specify a consistent, backward-compatible set of custom emojis. If an existing message contains a custom emoji that is not specified in customEmojis here, then the emoji cannot be displayed and the textual name will be displayed instead (including colons).

If you want to allow an emoji to be displayed if it's used in existing data, but not let users select it in new messages/reactions, set the hidden option to true for that emoji.

Example

1{
2 ":lol:": { url: "https://example.com/images/emoji-lol.svg" },
3 ":roomba-cat:": { url: "https://example.com/images/roomba-cat.gif" },
4 ":alert:": { url: "https://example.com/images/alert.gif", hidden: true },
5}

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 on the "Settings" page of the dashboard.

theme (optional)
: string | ThemeOptions

Overrides the theme used for this chat UI.

This only works with themes created in the Theme Editor. If you don't pass a theme name, we'll first check for a theme set in the user's role, and then fall back to using the default theme.

You can either pass the name of the theme you'd like to use, or a ThemeOptions object, which you can use to pass variables to your theme.

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 or turn off 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 on the "Settings" page of 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.

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.

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.

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.

Returns

Popup[]

hasValidCredentials

session.hasValidCredentials(): Promise<boolean>

Verifies whether the appId is valid.

Returns a Promise of a boolean, never rejects.

Returns

Promise<boolean>

onBrowserPermissionDenied

session.onBrowserPermissionDenied(handler): Subscription

Triggered when the user tried to do an action that requires explicit browser permission, but this permission was denied.

This can be caused by user actions such as the sharing a location, enabling desktop notifications, or trying to record a voice message. These features require the user to explicitly grant the browser permission.

This event can be triggered in two situations:

1. The browser showed the user a permission prompt, and the user picked "Deny". In this case, this event will have been preceded by onBrowserPermissionNeeded.

2. The user has denied the same permission in the past and the browser remembered this decision. In this case, the action will fail immediately and an onBrowserPermissionNeeded event will not have been emitted.

In either case, the user may be able to allow the permission in their browser settings. The intended use of this event is to show the user an alert or dialog telling them how.

Note: by default, TalkJS may display an error message in an alert if a permission is denied. If you listen to this event, then these messages are suppressed under the assumption that you will provide your own UI for this.

Parameters

handler
: (event: BrowserPermissionNeededEvent) => void

Returns

Subscription

onBrowserPermissionNeeded

session.onBrowserPermissionNeeded(handler): Subscription

Triggered when a browser permission prompt is about to be shown.

Certain features, such as sharing location, sending voice messages, or receiving notificatons, only work if the user has granted your app the relevant permissions. By default, TalkJS will trigger the browser's built-in permissions dialog the first time such a feature is used.

This event is triggered *just before* this browser permissions dialog is shown. This lets you show custom UI elements that let you show the user where to look, or explain that it's all safe.

If you return a promise from your event handler, then TalkJS will wait until this promise resolves before showing the permission dialog.

Note that it is not guaranteed that this event will trigger: It will only trigger if we are certain that a permission prompt is about to show, and unfortunately we can't be certain of that in all browsers. More explicitly, it will only trigger when the browser supports the [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API) with the given notification type.

Notably:

* Safari below 15.6 (2022) does not support the Permissions API at all

* Firefox does not support querying the "microphone" permission, which TalkJS needs for voice messages.

In these situations, this event will never trigger.

Parameters

handler
: ( event: BrowserPermissionNeededEvent ) => Promise<any> | void

Returns

Subscription

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
: (event: DesktopNotificationClickedEvent) => 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. If anything goes wrong, the promise will reject with a TalkError, which has a code property to indicate what went wrong. Possible values in this case 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(options): 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

interface PushRegistrationOptions

provider
: "fcm" | "apns"

The push message provider to use: Google's Firebase Cloud Messaging (fcm) or Apple's APNs (apns).

pushRegistrationId
: string

The APNs device token or the FCM registration token.

Returns

Promise<void>

unsetPushRegistration

session.unsetPushRegistration(options): 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

interface PushRegistrationOptions

provider
: "fcm" | "apns"

The push message provider to use: Google's Firebase Cloud Messaging (fcm) or Apple's APNs (apns).

pushRegistrationId
: string

The APNs device token or the FCM registration token.

Returns

Promise<void>

user

session.user(id): UserRef

Get a reference to a user, for use with the Realtime API

Parameters

id
: string

The ID of the user that you want to reference

Returns

UserRef

A UserRef for the user with that ID

Deprecated Methods

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

Method Overview

off Deprecated

Used to stop listening to specific TalkJS session events.

on Deprecated

Listens for an event

registerDevice Deprecated
syncThemeForLocalDev Deprecated

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

unregisterDevice Deprecated

Deprecated off (1)

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

Deprecated off (2)

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 (1)

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 https://gist.github.com/eteeselink/607e585eb40be76f2ed150d4090e5261

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

Deprecated on (2)

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, pushRegistrationId, }): 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 syncThemeForLocalDev

session.syncThemeForLocalDev(path)

Used to configure TalkJS to use a legacy 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.

Deprecated. We recommend switching to Custom Themes, which are substantially more powerful and do not have a practical need for a method like this.

Parameters

path
: string

The path to the legacy theme's CSS file

Returns

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.

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
: (unreadConversations: 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.

Method Overview

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
: (unreadConversations: 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
: (unreadConversations: UnreadConversation[]) => void

Returns

void

interface UnreadConversation

Used as part of Unreads​.on.

Properties

conversation
: ConversationData

The ConversationData of the unread conversation.

Always identical to lastMessage.conversation, which is maintained for compatibility reasons.

interface ConversationData

custom
: CustomData

Contains custom metadata for the conversation if it was set using ConversationBuilder​.custom.

Set any property to null to delete the existing value (if any). When omitted or undefined, the existing value remains unchanged. When sending custom: null all properties and values will be removed.

id
: string

The ID of the conversation

participants
: Record< string, { access: "Read" | "ReadWrite" } >

A map of the access rights for the participants in this conversation.

This property is not guaranteed to be complete. It always includes the current user, but does not always list other participants.

Specifically, ConversationData returned from the following functions will only include the current user: Session.onMessage, Session.onDesktopNotificationClicked, Session.unreads.onChange. In all other cases, this field contains every participant in the conversation.

Note on guest access: This field indicates a user's access as a participant. Guests always have "ReadWrite" access and are not included in this map

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

lastMessage
: Message

Contains the last Message for this conversation.

unreadMessageCount
: number

The number of unread messages in this conversation.

Note: Conversations with last activity before 15 June 2023 will have unreadMessageCount value set to 0 on initial load. It will be properly set after the next refresh

interface DesktopNotificationClickedEvent

Sent by Session​.onDesktopNotificationClicked when a user clicks on a browser notification.

Properties

conversation
: ConversationData

interface Message

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

Properties

attachment
: { url: string size: number dimensions?: { width: number height: number } } | null

Only given if the message's type equals "media". An object with the URL and filesize (in bytes) of the given file. Attachment dimensions (in px) are sometimes available for image and video attachments, used to set the size of the thumbnail before loading, to prevent content shift when loading media on slower connections.

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

Set any property to null to delete the existing value (if any). When omitted or undefined, the existing value remains unchanged.

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:

1[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
: UserSnapshot | 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 BrowserPermissionNeededEvent

Sent by Session​.onBrowserPermissionNeeded when a browser permission dialog is about to be shown to the user.

Method Overview

preventDefault

Cancel whatever user action caused the permission to be requested.

Properties

type
: BrowserPermission

The type of permission requested.

Note that more possible values may be added in the future, so make sure your handler can deal with unknown permission types gracefully.

preventDefault

browserPermissionNeededEvent.preventDefault()

Cancel whatever user action caused the permission to be requested.

For example, if a user wants to share their location for the first time so that this event is triggered, then if you call preventDefault(), no permission will be requested from the browser, the location sharing will be cancelled, and TalkJS will continue as if the location sharing button had not been clicked at all.

This may be useful if you're using this event to show custom UI elements that nudge users towards granting permission, and this UI has a "cancel" button.

Returns

void

interface BrowserPermissionDeniedEvent

Sent by Session​.onBrowserPermissionDenied when the user tried to do an action that require explicit browser permission, but it was denied.

Properties

type
: BrowserPermission

The type of permission that was denied.

Note that more possible values may be added in the future, so make sure your handler can deal with unknown permission types gracefully.

type PermissionType

A string that is one of "notifications" | "microphone" | "geolocation".

Used in BrowserPermissionNeeded­Event and BrowserPermissionDenied­Event

Note that more possible values may be added in the future, so make sure your handler can deal with unknown permission types gracefully.