diff --git a/sdk/javascript/additional-message-filtering.mdx b/sdk/javascript/additional-message-filtering.mdx index 6648ba35..aa891637 100644 --- a/sdk/javascript/additional-message-filtering.mdx +++ b/sdk/javascript/additional-message-filtering.mdx @@ -1,8 +1,42 @@ --- title: "Additional Message Filtering" +description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Filter by category and type +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setCategories(["message"]) + .setTypes(["image", "video", "audio", "file"]) + .setLimit(50) + .build(); + +// Unread messages only +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setUnread(true) + .setLimit(50) + .build(); + +// Threaded messages +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID("UID") + .setParentMessageId(parentId) + .setLimit(50) + .build(); + +// Fetch with pagination +messagesRequest.fetchPrevious().then(messages => { }); +messagesRequest.fetchNext().then(messages => { }); +``` + +**Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` + The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. @@ -1474,3 +1508,39 @@ let GUID: string = "GUID", + + +- **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering +- **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance +- **Use timestamps for sync**: `setUpdatedAfter()` helps sync local cache with server +- **Hide deleted messages in UI**: Use `hideDeletedMessages(true)` for cleaner message lists +- **Filter blocked users**: Use `hideMessagesFromBlockedUsers(true)` to respect user preferences +- **Reuse MessagesRequest**: Call `fetchPrevious()`/`fetchNext()` on the same object for pagination + + + +- **No messages returned** — Conflicting filters may cancel each other out. Simplify filters and add them one at a time to isolate the issue. +- **Missing message types** — Ensure the category matches the type (e.g., category `"message"` for type `"text"`). +- **Pagination not working** — Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls. Creating a new object resets pagination. +- **Thread replies included** — Add `.hideReplies(true)` to exclude thread messages from the main conversation. +- **Deleted messages showing** — Add `.hideDeletedMessages(true)` to filter them out. This is not enabled by default. + + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real-time + + + Understand message categories, types, and hierarchy + + + Work with threaded conversations + + diff --git a/sdk/javascript/advanced-overview.mdx b/sdk/javascript/advanced-overview.mdx index 7a8e791f..87376691 100644 --- a/sdk/javascript/advanced-overview.mdx +++ b/sdk/javascript/advanced-overview.mdx @@ -1,8 +1,48 @@ --- title: "Advanced" sidebarTitle: "Overview" +description: "Advanced SDK features including connection management, real-time listeners, login listeners, and WebSocket configuration." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Check connection status +CometChat.getConnectionStatus(); // "connected" | "connecting" | "disconnected" + +// Listen for connection changes +CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ + onConnected: () => console.log("Connected"), + onDisconnected: () => console.log("Disconnected") +})); + +// Listen for login events +CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ + onLoginSuccess: (user) => console.log("Logged in:", user), + onLogoutSuccess: () => console.log("Logged out") +})); +``` + This section helps you to know about the Connection Listeners. + +--- + +## Next Steps + + + + Monitor and respond to connection state changes + + + Manually manage WebSocket connections + + + Listen for login and logout events + + + Complete reference for all SDK listeners + + diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index f4b88d96..8525c434 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -1,7 +1,37 @@ --- title: "AI Agents" +description: "Integrate AI Agents into your app to enable intelligent, automated conversations with real-time streaming events and tool invocations." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Listen for real-time AI Agent events (streaming) +CometChat.addAIAssistantListener("LISTENER_ID", { + onAIAssistantEventReceived: (event) => console.log("Event:", event) +}); + +// Listen for persisted agentic messages +CometChat.addMessageListener("LISTENER_ID", { + onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg), + onAIToolResultReceived: (msg) => console.log("Tool result:", msg), + onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg) +}); + +// Cleanup +CometChat.removeAIAssistantListener("LISTENER_ID"); +CometChat.removeMessageListener("LISTENER_ID"); +``` + +**Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished + + + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) + + # AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). @@ -131,4 +161,44 @@ These events are received via the **`MessageListener`** after the run completes. CometChat.removeMessageListener(listnerId); ``` - \ No newline at end of file + + + + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + + +- **Register both listeners** — Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience. +- **Handle streaming progressively** — Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply. +- **Track run lifecycle** — Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing. +- **Remove listeners on cleanup** — Always call both `removeAIAssistantListener()` and `removeMessageListener()` when the component unmounts. +- **Handle tool calls gracefully** — Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation. + + + +- **No events received** — Ensure the AI Agent is configured in the CometChat Dashboard and the user is sending text messages (agents only respond to text). +- **`onAIAssistantEventReceived` not firing** — Verify the `AIAssistantListener` is registered after successful `CometChat.init()` and `login()`. +- **Agentic messages not arriving** — These come via `MessageListener` after the run completes. Make sure you've registered `onAIAssistantMessageReceived`, `onAIToolResultReceived`, and `onAIToolArgumentsReceived`. +- **Duplicate events** — Check that you're not registering multiple listeners with different IDs. Remove old listeners before adding new ones. +- **Streaming events arrive but no final message** — The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback. + + +--- + +## Next Steps + + + + Set up AI-powered chatbots for automated conversations + + + Automatically moderate messages with AI + + + AI-powered features like smart replies and conversation summaries + + + Send text messages that trigger AI Agent responses + + diff --git a/sdk/javascript/ai-moderation.mdx b/sdk/javascript/ai-moderation.mdx index 768de540..008d2d90 100644 --- a/sdk/javascript/ai-moderation.mdx +++ b/sdk/javascript/ai-moderation.mdx @@ -1,7 +1,36 @@ --- title: "AI Moderation" +description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Send message — check moderation status +CometChat.sendMessage(textMessage).then(message => { + const status = message.getModerationStatus(); + // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED +}); + +// Listen for moderation results +CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + // Handle APPROVED or DISAPPROVED + } +})); +``` + +**Supported types:** Text, Image, Video messages only +**Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com) + + ## Overview AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. @@ -300,5 +329,39 @@ Here's a complete implementation showing the full moderation flow: + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + + +- **Show pending state in UI** — When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed. +- **Handle disapproved messages gracefully** — Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened. +- **Register the listener early** — Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results. +- **Track pending messages** — Maintain a local map of pending message IDs so you can update the UI when moderation results arrive. +- **Test with moderation rules** — Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated. + + + +- **`onMessageModerated` never fires** — Ensure moderation is enabled in the CometChat Dashboard and rules are configured under Moderation > Rules. +- **All messages show `PENDING` but never resolve** — Check that your moderation rules are properly configured and the moderation service is active in your plan. +- **Custom messages not being moderated** — AI Moderation only supports Text, Image, and Video messages. Custom messages are not subject to moderation. +- **Moderation status is `undefined`** — You may be using an older SDK version that doesn't support moderation. Update to the latest version. +- **Disapproved messages still visible to recipients** — The SDK handles this automatically. If recipients still see blocked messages, verify your `onMessageModerated` handler is updating the UI correctly. + + ## Next Steps -After implementing AI Moderation, consider adding a reporting feature to allow users to flag messages they find inappropriate. For more details, see the [Flag Message](/sdk/javascript/flag-message) documentation. + + + + Allow users to report inappropriate messages manually + + + Build intelligent automated conversations with AI Agents + + + Smart replies, conversation summaries, and more + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index a70adfb5..54a20964 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -1,8 +1,44 @@ --- title: "All Real Time Listeners" +description: "Complete reference for all CometChat real-time listeners including User, Group, Message, and Call listeners." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// User Listener — online/offline presence +CometChat.addUserListener("ID", new CometChat.UserListener({ + onUserOnline: (user) => { }, + onUserOffline: (user) => { } +})); + +// Message Listener — messages, typing, receipts, reactions +CometChat.addMessageListener("ID", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => { }, + onMediaMessageReceived: (msg) => { }, + onTypingStarted: (indicator) => { }, + onMessagesRead: (receipt) => { } +})); + +// Group Listener — member join/leave/kick/ban/scope changes +CometChat.addGroupListener("ID", new CometChat.GroupListener({ ... })); + +// Call Listener — incoming/outgoing call events +CometChat.addCallListener("ID", new CometChat.CallListener({ ... })); + +// Always clean up +CometChat.removeUserListener("ID"); +CometChat.removeMessageListener("ID"); +CometChat.removeGroupListener("ID"); +CometChat.removeCallListener("ID"); +``` + + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + CometChat provides 4 listeners viz. @@ -25,7 +61,7 @@ To add the `UserListener`, you need to use the `addUserListener()` method provid ```js -var listenerID = "UNIQUE_LISTENER_ID"; +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ @@ -43,7 +79,7 @@ CometChat.addUserListener( ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID"; +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ @@ -530,3 +566,39 @@ CometChat.removeCallListener(listenerID); + + + +- **Use unique listener IDs** — Each listener must have a unique ID. Using the same ID for multiple listeners will overwrite the previous one, causing missed events. +- **Register listeners early** — Add listeners right after `CometChat.init()` and `login()` succeed so you don't miss any events. +- **Always clean up** — Remove all listeners when they're no longer needed (component unmount, page navigation, logout) to prevent memory leaks and duplicate callbacks. +- **Keep listener callbacks lightweight** — Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously. +- **Use specific listeners** — Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages. + + + +- **Events not firing** — Ensure listeners are registered after a successful `CometChat.init()` and `login()`. Listeners registered before init have no effect. +- **Duplicate events received** — You likely have multiple listeners registered with the same or different IDs. Check that you're removing old listeners before adding new ones. +- **Missing events after page navigation** — Listeners are removed when the component unmounts. Re-register them when the new component mounts. +- **`onMessagesDelivered` / `onMessagesRead` not triggering** — Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()`. +- **Call events not received** — Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized. + + +--- + +## Next Steps + + + + Handle incoming messages in real-time + + + Show when users are typing + + + Track online/offline status of users + + + Monitor SDK connection state changes + + diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 1df05717..2a4f6499 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -1,9 +1,30 @@ --- title: "Authentication" sidebarTitle: "Overview" +description: "Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Check existing session +const user = await CometChat.getLoggedinUser(); + +// Login with Auth Key (development only) +CometChat.login("UID", "AUTH_KEY").then(user => console.log("Logged in:", user)); + +// Login with Auth Token (production) +CometChat.login("AUTH_TOKEN").then(user => console.log("Logged in:", user)); + +// Logout +CometChat.logout().then(() => console.log("Logged out")); +``` + +**Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) +**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + ## Create User @@ -12,6 +33,26 @@ Before you log in a user, you must add the user to CometChat. 1. **For proof of concept/MVPs**: Create the user using the [CometChat Dashboard](https://app.cometchat.com). 2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app. +### Authentication Flow + +```mermaid +sequenceDiagram + participant User + participant YourApp as Your App + participant YourServer as Your Server + participant CometChat as CometChat + + User->>YourApp: Signs up / Logs in + YourApp->>YourServer: Authenticate user + YourServer->>CometChat: Create user (REST API, first time only) + CometChat-->>YourServer: User created + YourServer->>CometChat: Create Auth Token (REST API) + CometChat-->>YourServer: Auth Token + YourServer-->>YourApp: Return Auth Token + YourApp->>CometChat: CometChat.login(authToken) + CometChat-->>YourApp: User object (logged in) +``` + We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. @@ -32,11 +73,15 @@ The CometChat SDK maintains the session of the logged-in user within the SDK. Th This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [AuthToken](#login-using-auth-token) instead of an Auth Key to ensure enhanced security. + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + ```js -var UID = "UID"; -var authKey = "AUTH_KEY"; +const UID = "UID"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user) => { @@ -61,8 +106,8 @@ CometChat.getLoggedinUser().then( ```typescript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -85,6 +130,24 @@ CometChat.getLoggedinUser().then( + +```javascript +const UID = "UID"; +const authKey = "AUTH_KEY"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(UID, authKey); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + | Parameters | Description | @@ -105,7 +168,7 @@ This advanced authentication procedure does not use the Auth Key directly in you ```js -var authToken = "AUTH_TOKEN"; +const authToken = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( (user) => { @@ -130,7 +193,7 @@ CometChat.getLoggedinUser().then( ```typescript -var authToken: string = "AUTH_TOKEN"; +const authToken: string = "AUTH_TOKEN"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -153,6 +216,23 @@ CometChat.getLoggedinUser().then( + +```javascript +const authToken = "AUTH_TOKEN"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(authToken); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + | Parameter | Description | @@ -194,4 +274,69 @@ CometChat.logout().then( + +```javascript +try { + await CometChat.logout(); + console.log("Logout completed successfully"); +} catch (error) { + console.log("Logout failed with exception:", { error }); +} +``` + + + + +## Best Practices + + + + Before calling `login()`, use `CometChat.getLoggedinUser()` to check if a session already exists. This avoids unnecessary login calls and prevents session conflicts. + + + Auth Keys are convenient for development but expose your app to security risks in production. Always generate Auth Tokens server-side using the [REST API](https://api-explorer.cometchat.com/reference/create-authtoken) and pass them to the client. + + + Auth Tokens can expire. Implement a mechanism to detect login failures due to expired tokens and re-generate them from your server. Use the [Login Listener](/sdk/javascript/login-listener) to detect session changes. + + + Always call `CometChat.logout()` when your user signs out of your app. This clears the SDK session and stops real-time event delivery, preventing stale data and memory leaks. + + + +## Troubleshooting + + + + The user must be created in CometChat before they can log in. Create the user via the [Dashboard](https://app.cometchat.com) (testing) or [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) first. + + + Verify your Auth Key matches the one in your [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys. Ensure you haven't accidentally used the REST API Key instead. + + + Ensure `CometChat.init()` has been called and completed successfully before calling `login()`. Verify your App ID and Region are correct. + + + This can happen if the SDK session was not persisted. Ensure `init()` is called on every app load before checking `getLoggedinUser()`. The SDK stores session data in the browser — clearing browser storage will clear the session. + + + +--- + +## Next Steps + + + + Send your first text, media, or custom message + + + Install and initialize the CometChat SDK + + + Create, update, and delete users programmatically + + + Listen for login and logout events in real-time + + diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 738e07ab..5baa2dca 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -1,8 +1,30 @@ --- title: "Block Users" +description: "Block and unblock users, and retrieve the list of blocked users using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Block users +await CometChat.blockUsers(["UID1", "UID2"]); + +// Unblock users +await CometChat.unblockUsers(["UID1", "UID2"]); + +// Get blocked users list +let request = new CometChat.BlockedUsersRequestBuilder().setLimit(30).build(); +let blockedUsers = await request.fetchNext(); +``` + +**Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Block Users @@ -11,9 +33,9 @@ title: "Block Users" You can block users using the `blockUsers()` method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be blocked. - + ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( list => { @@ -28,7 +50,7 @@ list => { ```typescript -var usersList: String[] = ["UID1", "UID2", "UID3"]; +const usersList: String[] = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( (list: Object) => { @@ -41,6 +63,20 @@ CometChat.blockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +try { + const list = await CometChat.blockUsers(usersList); + console.log("users list blocked", { list }); +} catch (error) { + console.log("Blocking user fails with error", error); +} +``` + + + It returns a Array which contains `UID's` as the keys and "success" or "fail" as the value based on if the block operation for the `UID` was successful or not. @@ -52,9 +88,9 @@ It returns a Array which contains `UID's` as the keys and "success" or "fail" as You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be unblocked. - + ```javascript -var usersList = ["UID1", "UID2", "UID3"]; +const usersList = ["UID1", "UID2", "UID3"]; CometChat.unblockUsers(usersList).then( list => { @@ -69,7 +105,7 @@ list => { ```typescript -var usersList: String[] = ["UID1", "UID2", "UID3"]; +const usersList: String[] = ["UID1", "UID2", "UID3"]; CometChat.unblockUsers(usersList).then( (list: Object) => { @@ -82,6 +118,20 @@ CometChat.unblockUsers(usersList).then( + +```javascript +const usersList = ["UID1", "UID2", "UID3"]; + +try { + const list = await CometChat.unblockUsers(usersList); + console.log("users list unblocked", { list }); +} catch (error) { + console.log("unblocking user fails with error", error); +} +``` + + + It returns a Array which contains `UID's` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. @@ -188,10 +238,10 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the `BlockedUsersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `User` objects containing n number of blocked users where N is the limit set in the builder class. - + ```javascript -var limit = 30; -var blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() +const limit = 30; +const blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() .setLimit(limit) .build(); blockedUsersRequest.fetchNext().then( @@ -224,3 +274,41 @@ blockedUsersRequest.fetchNext().then( + +--- + + + + - **Block in batches** — You can block multiple users in a single call by passing an array of UIDs. This is more efficient than blocking one at a time. + - **Update UI immediately** — After blocking/unblocking, update your user list and conversation list to reflect the change. + - **Use direction filters** — Use `BLOCKED_BY_ME` to show users you've blocked, `HAS_BLOCKED_ME` to detect who blocked you, or `BOTH` for the full picture. + - **Hide blocked users in lists** — Use `hideBlockedUsers(true)` in `UsersRequestBuilder` to automatically exclude blocked users from user lists. + - **Handle block status in messaging** — Messages from blocked users won't be delivered. Inform users that blocking prevents all communication. + + + - **Block operation returns "fail" for a UID** — The UID may not exist or may already be blocked. Verify the UID is correct. + - **Still receiving messages after blocking** — Ensure the block operation completed successfully. Check the response object for "success" status on each UID. + - **Blocked user list empty** — Verify the direction filter. Default is `BOTH`, but if you set `HAS_BLOCKED_ME` and no one has blocked you, the list will be empty. + - **Unblock not working** — Ensure you're passing the correct UIDs. The unblock operation only works on users you've blocked (`BLOCKED_BY_ME`). + - **Blocked user still appears in user list** — Use `hideBlockedUsers(true)` in your `UsersRequestBuilder` to filter them out automatically. + + + +--- + +## Next Steps + + + + Fetch and filter user lists + + + Track online/offline status of users + + + Create, update, and delete users + + + Report inappropriate messages from users + + diff --git a/sdk/javascript/call-logs.mdx b/sdk/javascript/call-logs.mdx index 74f2b87a..9fb4adda 100644 --- a/sdk/javascript/call-logs.mdx +++ b/sdk/javascript/call-logs.mdx @@ -1,8 +1,32 @@ --- title: "Call Logs" +description: "Fetch, filter, and retrieve call history including duration, participants, and recording status using the CometChat Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch call logs +let request = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); + +let logs = await request.fetchNext(); + +// Get details for a specific call session +let details = await CometChatCalls.getCallDetails("SESSION_ID", authToken); +``` + +**Filters:** `setCallType()`, `setCallStatus()`, `setCallCategory()`, `setCallDirection()`, `setHasRecording()`, `setUid()`, `setGuid()` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [Dashboard](https://app.cometchat.com) + ## Overview @@ -40,7 +64,7 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() ### Fetch Next -The**`fetchNext()`**method retrieves the next set of call logs. +The `fetchNext()` method retrieves the next set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -60,7 +84,7 @@ callLogRequestBuilder.fetchNext() ### Fetch Previous -The**`fetchPrevious()`**method retrieves the previous set of call logs. +The `fetchPrevious()` method retrieves the previous set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -80,17 +104,84 @@ callLogRequestBuilder.fetchPrevious() ## Get Call Details -To retrieve the specific details of a call, use the**`getCallDetails()`**method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. +To retrieve the specific details of a call, use the `getCallDetails()` method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. + + ```javascript -var sessionID = "SESSION_ID"; -CometChatCalls.getCallDetails(sessionID, authToken) -.then((callLogs: Array) => { - console.log(callLogs); - }) - .catch(err => { - console.log(err); - }); +const sessionID = "SESSION_ID"; +CometChatCalls.getCallDetails(sessionID, authToken).then( + (callLogs) => { + console.log("Call details:", callLogs); + }, + (error) => { + console.log("Error fetching call details:", error); + } +); ``` + + +```typescript +const sessionID: string = "SESSION_ID"; +CometChatCalls.getCallDetails(sessionID, authToken).then( + (callLogs: Array) => { + console.log("Call details:", callLogs); + }, + (error: any) => { + console.log("Error fetching call details:", error); + } +); +``` + + +```javascript +const sessionID = "SESSION_ID"; +try { + const callLogs = await CometChatCalls.getCallDetails(sessionID, authToken); + console.log("Call details:", callLogs); +} catch (error) { + console.log("Error fetching call details:", error); +} +``` + + + +Note: Replace `"SESSION_ID"` with the ID of the session you are interested in. + +--- + + + + - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and implement pagination with `fetchNext()` / `fetchPrevious()` for large call histories. + - **Filter by category** — Use `setCallCategory("call")` or `setCallCategory("meet")` to separate regular calls from meetings. + - **Cache auth tokens** — Store the user's auth token rather than fetching it repeatedly for each call log request. + - **Handle empty results** — Always check if the returned array is empty before processing call logs. + - **Use appropriate filters** — Combine filters like `setCallDirection()`, `setCallStatus()`, and `setHasRecording()` to narrow down results efficiently. + + + - **Empty call logs returned** — Verify the auth token is valid and belongs to a user who has participated in calls. Check that filters aren't too restrictive. + - **Auth token errors** — Ensure you're using `loggedInUser.getAuthToken()` and that the user is logged in before fetching call logs. + - **Missing recordings** — Use `setHasRecording(true)` to filter only calls with recordings. Recordings may take time to process after a call ends. + - **Pagination not working** — Make sure you're reusing the same `CallLogRequestBuilder` instance for `fetchNext()` / `fetchPrevious()` calls. + - **Session ID not found** — The session ID must match an existing call session. Verify the session ID is correct and the call has completed. + + + +--- -Note: Replace**`"SESSION_ID"`**with the ID of the session you are interested in. +## Next Steps + + + + Implement the complete ringing call flow + + + Record audio and video calls + + + Start call sessions without the ringing flow + + + Install and initialize the Calls SDK + + diff --git a/sdk/javascript/calling-overview.mdx b/sdk/javascript/calling-overview.mdx index 18bc0ea6..ce140ded 100644 --- a/sdk/javascript/calling-overview.mdx +++ b/sdk/javascript/calling-overview.mdx @@ -1,8 +1,26 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Overview of CometChat voice and video calling capabilities including ringing, direct call sessions, and standalone calling." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Choose your calling approach: +- **Ringing** → [Default Call](/sdk/javascript/default-call) — Full call flow with notifications, accept/reject +- **Call Session** → [Direct Call](/sdk/javascript/direct-call) — Session-based calling with custom UI +- **Standalone** → [Standalone Calling](/sdk/javascript/standalone-calling) — Calls SDK only, no Chat SDK needed + +```bash +# Install Calls SDK +npm install @cometchat/calls-sdk-javascript +``` + +**Features:** Recording, Virtual Background, Screen Sharing, Custom CSS, Call Logs, Session Timeout + + ## Overview CometChat provides voice and video calling capabilities for your web application. This guide helps you choose the right implementation approach based on your use case. @@ -96,3 +114,35 @@ Use this when you want: Configure automatic call termination when participants are inactive. + +--- + + + + - **Choose the right approach** — Use Ringing for full call experience with notifications, Call Session for custom UI, and Standalone for minimal SDK footprint. + - **Initialize both SDKs** — For Ringing and Call Session flows, ensure both Chat SDK and Calls SDK are initialized before starting calls. + - **Handle all call states** — Implement handlers for accepted, rejected, cancelled, busy, and ended states to provide a complete user experience. + - **Clean up resources** — Always call `CometChatCalls.endSession()` when leaving a call to release camera, microphone, and network resources. + - **Test on multiple devices** — Voice and video calling behavior can vary across browsers and devices. Test thoroughly on your target platforms. + + + - **No audio/video** — Check browser permissions for camera and microphone. Ensure the user granted access when prompted. + - **Call not connecting** — Verify both participants have initialized the Calls SDK and are using the same session ID. + - **One-way audio** — This often indicates a firewall or NAT issue. CometChat uses TURN servers, but corporate networks may block WebRTC traffic. + - **Poor call quality** — Check network bandwidth. Video calls require stable connections. Consider offering audio-only fallback for poor connections. + - **Calls SDK not found** — Ensure `@cometchat/calls-sdk-javascript` is installed and imported correctly. + + + +--- + +## Next Steps + + + + Install and initialize the Calls SDK + + + Implement the complete ringing call flow + + diff --git a/sdk/javascript/calling-setup.mdx b/sdk/javascript/calling-setup.mdx index 7cd07247..2ca0ea53 100644 --- a/sdk/javascript/calling-setup.mdx +++ b/sdk/javascript/calling-setup.mdx @@ -1,8 +1,33 @@ --- title: "Setup" +description: "Install and initialize the CometChat Calls SDK for JavaScript to enable voice and video calling in your application." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +npm install @cometchat/calls-sdk-javascript +``` + +```javascript +import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; + +const callAppSetting = new CometChatCalls.CallAppSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build(); + +CometChatCalls.init(callAppSetting).then(() => console.log("Calls SDK ready")); +``` + +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) + + + +`CometChatCalls.init()` must be called before any other Calls SDK method. Make sure the Chat SDK is also initialized via `CometChat.init()` first (unless using [Standalone Calling](/sdk/javascript/standalone-calling)). + ## Get your Application Keys @@ -115,3 +140,41 @@ Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` w | Parameter | Description | | ----------------- | ---------------------------------------- | | `callAppSettings` | An object of the `CallAppSettings` class | + +--- + + + + - **Initialize once** — Call `CometChatCalls.init()` only once at app startup, typically in your main entry file (index.js, App.js). + - **Initialize Chat SDK first** — Unless using [Standalone Calling](/sdk/javascript/standalone-calling), always initialize the Chat SDK (`CometChat.init()`) before the Calls SDK. + - **Handle initialization errors** — Always implement error handling for the init promise to catch configuration issues early. + - **Use environment variables** — Store App ID and Region in environment variables rather than hardcoding them. + - **Verify initialization** — Before making any Calls SDK method calls, ensure initialization completed successfully. + + + - **"CometChatCalls is not initialized"** — Ensure `CometChatCalls.init()` completed successfully before calling other methods. Check that the promise resolved without errors. + - **Invalid App ID or Region** — Verify your App ID and Region match exactly what's shown in the [CometChat Dashboard](https://app.cometchat.com). Region is case-sensitive (e.g., "us", "eu"). + - **CORS errors** — If using a custom host, ensure your domain is whitelisted in the CometChat Dashboard under App Settings. + - **Module not found** — Verify the package is installed correctly with `npm list @cometchat/calls-sdk-javascript`. Try removing node_modules and reinstalling. + - **Chat SDK not initialized** — If you see errors about missing user context, ensure `CometChat.init()` and `CometChat.login()` completed before initializing the Calls SDK. + + + +--- + +## Next Steps + + + + Implement the complete ringing call flow + + + Start call sessions without the ringing flow + + + Use Calls SDK without the Chat SDK + + + Compare calling approaches and features + + diff --git a/sdk/javascript/connection-status.mdx b/sdk/javascript/connection-status.mdx index 7c67128b..839bc4bf 100644 --- a/sdk/javascript/connection-status.mdx +++ b/sdk/javascript/connection-status.mdx @@ -1,8 +1,27 @@ --- title: "Connection Status" +description: "Monitor real-time WebSocket connection status and respond to connectivity changes using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Get current status: "connecting" | "connected" | "disconnected" +const status = CometChat.getConnectionStatus(); + +// Listen for connection changes +CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ + onConnected: () => console.log("Connected"), + inConnecting: () => console.log("Connecting..."), + onDisconnected: () => console.log("Disconnected") +})); + +// Cleanup +CometChat.removeConnectionListener("LISTENER_ID"); +``` + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. @@ -74,14 +93,14 @@ You can also get the current connection status by using `getConnectionStatus` pr ```javascript -var connectionStatus = CometChat.getConnectionStatus(); +const connectionStatus = CometChat.getConnectionStatus(); ``` ```typescript -var connectionStatus: string = CometChat.getConnectionStatus(); +const connectionStatus: string = CometChat.getConnectionStatus(); ``` @@ -93,3 +112,43 @@ The `CometChat.getConnectionStatus` method will return either of the below 3 val 1. connecting 2. connected 3. disconnected + + + +Always remove connection listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + + +- **Register early** — Add the connection listener right after `CometChat.init()` succeeds, ideally in your app's entry point, so you catch all connection state changes. +- **Show connection status in UI** — Display a banner or indicator when the connection is `"disconnected"` or `"connecting"` so users know messages may be delayed. +- **Queue actions during disconnection** — If the connection drops, queue user actions (like sending messages) and retry once `onConnected` fires. +- **Remove listeners on cleanup** — Always call `CometChat.removeConnectionListener()` when the component unmounts or the app shuts down. +- **Don't poll `getConnectionStatus()`** — Use the listener-based approach instead. Polling adds unnecessary overhead when the SDK already pushes state changes. + + + +- **Listener never fires** — Ensure you register the listener after a successful `CometChat.init()` call. Registering before init has no effect. +- **Stuck in "connecting" state** — Check your network connection and firewall settings. Also verify your `appId` and `region` are correct in the init configuration. +- **Frequent disconnections** — This usually indicates network instability. The SDK automatically reconnects, but if it persists, check for WebSocket-blocking proxies or VPNs. +- **`getConnectionStatus()` returns `undefined`** — The SDK hasn't been initialized yet. Call `CometChat.init()` first. +- **Multiple `onConnected` callbacks** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. + + +--- + +## Next Steps + + + + Manually manage WebSocket connections + + + Listen for login and logout events + + + Complete reference for all SDK listeners + + + Install and initialize the CometChat SDK + + diff --git a/sdk/javascript/create-group.mdx b/sdk/javascript/create-group.mdx index 29eed3de..c2a08be2 100644 --- a/sdk/javascript/create-group.mdx +++ b/sdk/javascript/create-group.mdx @@ -1,8 +1,29 @@ --- title: "Create A Group" +description: "Create public, private, or password-protected groups and optionally add members during creation using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Create a group +let group = new CometChat.Group("GUID", "Group Name", CometChat.GROUP_TYPE.PUBLIC, ""); +let createdGroup = await CometChat.createGroup(group); + +// Create group with members +let members = [new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT)]; +let result = await CometChat.createGroupWithMembers(group, members, []); +``` + +**Group types:** `PUBLIC` | `PASSWORD` | `PRIVATE` +**Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Create a Group @@ -24,14 +45,14 @@ The `groupType` needs to be either of the below 3 values: 3.`CometChat.GROUP_TYPE.PRIVATE` - + ```javascript -var GUID = "GUID"; -var groupName = "Hello Group!"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var password = ""; +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; -var group = new CometChat.Group(GUID, groupName, groupType, password); +const group = new CometChat.Group(GUID, groupName, groupType, password); CometChat.createGroup(group).then( group => { @@ -46,12 +67,12 @@ CometChat.createGroup(group).then( ```typescript -var GUID: string = "GUID"; -var groupName: string = "Hello Group!"; -var groupType: string = CometChat.GROUP_TYPE.PUBLIC; -var password: string = ""; +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const password: string = ""; -var group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType, password); CometChat.createGroup(group).then( (group: CometChat.Group) => { @@ -64,6 +85,25 @@ CometChat.createGroup(group).then( + +```javascript +const GUID = "GUID"; +const groupName = "Hello Group!"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const password = ""; + +const group = new CometChat.Group(GUID, groupName, groupType, password); + +try { + const createdGroup = await CometChat.createGroup(group); + console.log("Group created successfully:", createdGroup); +} catch (error) { + console.log("Group creation failed with exception:", error); +} +``` + + + The createGroup() method takes the following parameters: @@ -148,6 +188,29 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( + +```javascript +let GUID = "cometchat-guid-11"; +let UID = "cometchat-uid-1"; +let groupName = "Hello Group!"; +let groupType = CometChat.GROUP_TYPE.PUBLIC; + +let group = new CometChat.Group(GUID, groupName, groupType); +let members = [ + new CometChat.GroupMember(UID, CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +]; +let banMembers = ["cometchat-uid-2"]; + +try { + const response = await CometChat.createGroupWithMembers(group, members, banMembers); + console.log("Group created successfully", response); +} catch (error) { + console.log("Some error occured while creating group", error); +} +``` + + + This method returns an Object which has two keys: `group` & `members` . The group key has the Group Object which contains all the information of the group which is created. The members key has the `UID` of the users and the value will either be `success` or an `error` message describing why the operation to add/ban the user failed. @@ -171,3 +234,42 @@ This method returns an Object which has two keys: `group` & `members` . The grou | scope | Yes | Scope of the logged in user. Can be: 1. Admin 2. Moderator 3. Participant | | membersCount | No | The number of members in the groups | | tags | Yes | A list of tags to identify specific groups. | + + +--- + + + + - **Use meaningful GUIDs** — Choose descriptive, unique GUIDs (e.g., `"project-alpha-team"`) that are easy to reference in your codebase. + - **Set group type carefully** — Group type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE based on your use case. + - **Add members at creation** — Use `createGroupWithMembers()` to add initial members in a single API call instead of creating the group and adding members separately. + - **Store metadata** — Use the `metadata` field to store custom data (e.g., project ID, department) rather than encoding it in the group name. + - **Handle GUID conflicts** — If a GUID already exists, creation will fail. Check for existing groups or use unique identifiers. + + + - **"GUID already exists" error** — A group with that GUID already exists. Use a different GUID or retrieve the existing group. + - **"User not authorized" error** — The logged-in user may not have permission to create groups. Check your app's role settings in the Dashboard. + - **Members not added during creation** — Check the response object's `members` key. Individual member additions can fail (e.g., invalid UID) while the group creation succeeds. + - **Password group not requiring password** — Ensure `groupType` is set to `CometChat.GROUP_TYPE.PASSWORD` and a non-empty password is provided. + - **GUID validation error** — GUIDs can only contain alphanumeric characters, underscores, and hyphens. No spaces or special characters. + + + +--- + +## Next Steps + + + + Join public, private, or password-protected groups + + + Add users to an existing group + + + Fetch and filter group lists + + + Overview of all group management features + + diff --git a/sdk/javascript/custom-css.mdx b/sdk/javascript/custom-css.mdx index 56698ccf..363177b1 100644 --- a/sdk/javascript/custom-css.mdx +++ b/sdk/javascript/custom-css.mdx @@ -1,8 +1,26 @@ --- title: "Custom CSS" +description: "Customize the CometChat calling UI with custom CSS classes for buttons, video containers, name labels, and grid layouts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```css +/* Key CSS classes for call UI customization */ +.cc-main-container { } /* Outermost call container */ +.cc-bottom-buttons-container { } /* Bottom action buttons bar */ +.cc-name-label { } /* User name text */ +.cc-video-container { } /* Video feed container */ +.cc-end-call-icon-container { } /* End call button */ +.cc-audio-icon-container { } /* Audio toggle button */ +.cc-video-icon-container { } /* Video toggle button */ +.cc-screen-share-icon-container { } /* Screen share button */ +``` + +**Modes:** `DEFAULT` | `TILE` | `SPOTLIGHT` + Passing custom CSS allows you to personalize and enhance the user interface of the call screen. @@ -170,3 +188,39 @@ The above example results in the below output:- * Avoid resizing the grid container. Altering the grid container’s dimensions can negatively impact the grid layout, leading to undesirable visual distortions. By following these recommendations, you can maintain a stable and visually consistent grid layout. + + +- **Only use documented CSS classes** — Applying styles to undocumented internal classes may break with SDK updates. Stick to the classes listed in this guide. +- **Don't resize the grid container** — Altering the grid container dimensions can break the layout. Only customize colors, borders, and visibility. +- **Use `!important` sparingly** — Some SDK styles may need `!important` to override, but overusing it makes maintenance harder. +- **Test across modes** — CSS changes may look different in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes. Test all three. +- **Keep button sizes accessible** — When customizing button dimensions, ensure they remain large enough for easy interaction (minimum 44x44px for touch targets). + + + +- **CSS changes not applying** — The SDK may use inline styles or higher-specificity selectors. Try adding `!important` to your rules. +- **Layout breaks after customization** — You may have resized the grid container or applied conflicting `display` or `position` properties. Revert and apply changes incrementally. +- **Styles only work in one mode** — Some CSS classes are mode-specific. Test in `DEFAULT`, `TILE`, and `SPOTLIGHT` modes to ensure consistency. +- **Muted button styles not showing** — Use the `-muted` variant classes (e.g., `cc-audio-icon-container-muted`) for muted state styling. +- **Custom styles disappear on SDK update** — If the SDK updates internal class names, your custom CSS may stop working. Pin your SDK version and test after updates. + + + +--- + +## Next Steps + + + + Customize video call layout and participant tiles + + + Apply blur or custom image backgrounds during calls + + + Enable screen sharing and presentation mode + + + Overview of all calling features and approaches + + diff --git a/sdk/javascript/default-call.mdx b/sdk/javascript/default-call.mdx index 180de4d7..2ed0138a 100644 --- a/sdk/javascript/default-call.mdx +++ b/sdk/javascript/default-call.mdx @@ -1,7 +1,38 @@ --- title: "Ringing" +description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept/reject/cancel functionality, and call session management." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Initiate a call +const call = new CometChat.Call("UID", CometChat.CALL_TYPE.VIDEO, CometChat.RECEIVER_TYPE.USER); +await CometChat.initiateCall(call); + +// Listen for call events +CometChat.addCallListener("ID", new CometChat.CallListener({ + onIncomingCallReceived: (call) => { /* show incoming UI */ }, + onOutgoingCallAccepted: (call) => { /* start session */ }, + onOutgoingCallRejected: (call) => { /* dismiss UI */ }, + onIncomingCallCancelled: (call) => { /* dismiss UI */ } +})); + +// Accept / Reject / Cancel +await CometChat.acceptCall(sessionId); +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.REJECTED); +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.CANCELLED); +``` + +**Flow:** Initiate → Receiver notified → Accept/Reject → Start session + + + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) + + ## Overview This section explains how to implement a complete calling workflow with ringing functionality, including incoming/outgoing call UI, call acceptance, rejection, and cancellation. Previously known as **Default Calling**. @@ -518,3 +549,46 @@ CometChat.rejectCall(sessionId, status).then( ``` + + + +Always remove call listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + + + + - **Store session ID** — Save the session ID from `initiateCall()` response immediately. You'll need it for accept, reject, cancel, and starting the session. + - **Handle all call states** — Implement handlers for all listener events (accepted, rejected, cancelled, busy, ended) to provide a complete user experience. + - **Show appropriate UI** — Display outgoing call UI after `initiateCall()`, incoming call UI in `onIncomingCallReceived()`, and dismiss UI in rejection/cancellation callbacks. + - **Clean up on unmount** — Remove call listeners when the component unmounts or when navigating away from the call screen. + - **Handle busy state** — Check if the user is already on a call before accepting a new one. Use `CALL_STATUS.BUSY` to inform the caller. + + + - **Call not received** — Verify the receiver is logged in and has registered the call listener. Check that the receiver UID/GUID is correct. + - **Duplicate call events** — Ensure you're using unique listener IDs and removing listeners when no longer needed. Multiple registrations with the same ID replace the previous listener. + - **Session not starting after accept** — After `acceptCall()` succeeds, you must generate a call token and call `startSession()`. The accept only signals intent, it doesn't start the media session. + - **Call stuck in ringing state** — Implement timeout logic to auto-cancel calls that aren't answered within a reasonable time (e.g., 30-60 seconds). + - **"Call already in progress" error** — Use `CometChat.getActiveCall()` to check for existing calls before initiating a new one. + + + +--- + +## Next Steps + + + + Manage call sessions, tokens, and settings + + + Retrieve and display call history + + + Record audio and video calls + + + Install and initialize the Calls SDK + + diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index b91669f6..edfe350d 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -1,8 +1,30 @@ --- title: "Delete A Conversation" +description: "Delete user or group conversations for the logged-in user using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete user conversation +await CometChat.deleteConversation("UID", "user"); + +// Delete group conversation +await CometChat.deleteConversation("GUID", "group"); +``` + +**Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation) to delete for all participants. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted conversations cannot be recovered for the logged-in user. + In case you want to delete a conversation, you can use the `deleteConversation()` method. @@ -79,3 +101,36 @@ The `deleteConversation()` method takes the following parameters: | ---------------- | --------------------------------------------------------------------------------- | -------- | | conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | | conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | + + +- **Confirm before deleting**: Always show a confirmation dialog before deleting conversations +- **Update UI immediately**: Remove the conversation from the list optimistically, then handle errors +- **Handle errors gracefully**: If deletion fails, restore the conversation in the UI +- **Clear local cache**: If you cache conversations locally, remove them after successful deletion + + + +- **Conversation still visible after deletion** — Refresh the conversation list after deletion. Update your UI immediately on success. +- **Delete fails** — Verify the UID or GUID exists and is correct. +- **Other user still sees messages** — The SDK deletes for the logged-in user only. Use the REST API to delete for all participants. +- **"Conversation not found" error** — The conversation may already be deleted, or the `conversationType` doesn't match. Ensure it's `user` or `group` as appropriate. + + +--- + +## Next Steps + + + + Fetch and filter conversation lists + + + Delete individual messages from conversations + + + Show when users are typing in conversations + + + Track message delivery and read status + + diff --git a/sdk/javascript/delete-group.mdx b/sdk/javascript/delete-group.mdx index 54bcf413..ccb2aeef 100644 --- a/sdk/javascript/delete-group.mdx +++ b/sdk/javascript/delete-group.mdx @@ -1,17 +1,36 @@ --- title: "Delete A Group" +description: "Delete a group permanently using the CometChat JavaScript SDK. Only group admins can perform this operation." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete a group (admin only) +await CometChat.deleteGroup("GUID"); +``` + +**Requirement:** Logged-in user must be an Admin of the group. + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted groups and their messages cannot be recovered. + ## Delete a Group To delete a group you need to use the `deleteGroup()` method. The user must be an `Admin` of the group they are trying to delete. - + ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.deleteGroup(GUID).then( response => { @@ -26,7 +45,7 @@ response => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.deleteGroup(GUID).then( (response: boolean) => { @@ -39,6 +58,20 @@ CometChat.deleteGroup(GUID).then( + +```javascript +const GUID = "GUID"; + +try { + const response = await CometChat.deleteGroup(GUID); + console.log("Group deleted successfully:", response); +} catch (error) { + console.log("Group delete failed with exception:", error); +} +``` + + + The `deleteGroup()` method takes the following parameters: @@ -46,3 +79,40 @@ The `deleteGroup()` method takes the following parameters: | Parameter | Description | | --------- | ---------------------------------------------- | | `GUID` | The GUID of the group you would like to delete | + + +--- + + + + - **Confirm before deleting** — Always show a confirmation dialog. Group deletion is irreversible and removes all messages and member associations. + - **Verify admin status** — Only group admins can delete groups. Check the user's scope before showing the delete option in your UI. + - **Notify members** — Consider sending a final message or notification before deleting so members are aware. + - **Clean up local state** — After deletion, remove the group from local caches, conversation lists, and any UI references. + + + - **"Not authorized" error** — Only admins can delete groups. Verify the logged-in user's scope is `ADMIN` for this group. + - **Group not found** — The GUID may be incorrect or the group was already deleted. Verify the GUID exists. + - **Members still see the group** — Other members will receive a group deletion event via `GroupListener`. Ensure they handle `onGroupMemberLeft` or similar cleanup. + - **Deletion seems to hang** — Check network connectivity. The operation requires a server round-trip. + + + +--- + +## Next Steps + + + + Update group name, icon, description, and metadata + + + Leave a group you are a member of + + + Create public, private, or password-protected groups + + + Overview of all group management features + + diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index d84b0761..400c3916 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -1,8 +1,35 @@ --- title: "Delete A Message" +description: "Delete messages, receive real-time deletion events, and handle missed deletion events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete a message +await CometChat.deleteMessage(messageId); + +// Listen for real-time deletions +CometChat.addMessageListener("ID", new CometChat.MessageListener({ + onMessageDeleted: (message) => { + console.log("Deleted:", message.getId(), message.getDeletedAt()); + } +})); +``` + +**Who can delete:** Message sender, Group admin, Group moderator +**Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + + +This operation is irreversible. Deleted messages cannot be recovered. + While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: @@ -16,7 +43,7 @@ While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is s In case you have to delete a message, you can use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. - + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; @@ -46,6 +73,20 @@ CometChat.deleteMessage(messageId).then( + +```javascript +let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; + +try { + const message = await CometChat.deleteMessage(messageId); + console.log("Message deleted", message); +} catch (error) { + console.log("Message delete failed with error:", error); +} +``` + + + Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. @@ -118,3 +159,27 @@ For the message deleted event, in the `Action` object received, the following fi In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + + + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +--- + +## Next Steps + + + + Edit sent messages in conversations + + + Send text, media, and custom messages + + + Listen for incoming messages in real-time + + + Report inappropriate messages + + diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 464e319f..446e577f 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -1,8 +1,40 @@ --- title: "Delivery & Read Receipts" +description: "Learn how to mark messages as delivered, read, or unread and receive real-time receipt events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Mark message as delivered (pass message object) +await CometChat.markAsDelivered(message); +// Mark message as read (pass message object) +await CometChat.markAsRead(message); + +// Mark entire conversation as read +await CometChat.markConversationAsRead("USER_UID", "user"); + +// Mark message as unread +await CometChat.markMessageAsUnread(message); + +// Listen for receipt events +CometChat.addMessageListener("receipts", new CometChat.MessageListener({ + onMessagesDelivered: (receipt) => { }, + onMessagesRead: (receipt) => { }, + onMessagesDeliveredToAll: (receipt) => { }, // Group only + onMessagesReadByAll: (receipt) => { } // Group only +})); +``` + + +Delivery and read receipts let you track whether messages have been delivered to and read by recipients. This page covers marking messages as delivered, read, or unread, and receiving real-time receipt events. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Mark Messages as Delivered @@ -27,10 +59,10 @@ Ideally, you would like to mark all the messages as delivered for any conversati ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_RECEIVER_UID"; +const receiverType = "user"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -38,10 +70,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_RECEIVER_GUID"; +const receiverType = "group"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -49,10 +81,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -60,10 +92,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); ``` @@ -122,10 +154,10 @@ CometChat.markAsDelivered( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as delivered success."); @@ -143,10 +175,10 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as delivered success."); @@ -238,8 +270,8 @@ This method will mark all messages in the conversation as delivered. ```javascript -var conversationWith = "USER_UID"; -var conversationType = "user"; +const conversationWith = "USER_UID"; +const conversationType = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { @@ -254,8 +286,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```javascript -var conversationWith = "GROUP_GUID"; -var conversationType = "group"; +const conversationWith = "GROUP_GUID"; +const conversationType = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response) => { @@ -270,8 +302,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "USER_UID"; -var conversationType: string = "user"; +const conversationWith: string = "USER_UID"; +const conversationType: string = "user"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { @@ -286,8 +318,8 @@ CometChat.markConversationAsDelivered(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "GROUP_GUID"; -var conversationType: string = "group"; +const conversationWith: string = "GROUP_GUID"; +const conversationType: string = "group"; CometChat.markConversationAsDelivered(conversationWith, conversationType).then( (response: string) => { @@ -324,10 +356,10 @@ Ideally, you would like to mark all the messages as read for any conversation wh ```javascript -var messageId = "MESSAGE_ID"; -var receiverId = "MESSAGE_SENDER_UID"; -var receiverType = "user"; -var senderId = "MESSAGE_SENDER_UID"; +const messageId = "MESSAGE_ID"; +const receiverId = "MESSAGE_SENDER_UID"; +const receiverType = "user"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -335,9 +367,9 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```javascript -var receiverId = "MESSAGE_RECEIVER_GUID"; -var receiverType = "group"; -var senderId = "MESSAGE_SENDER_UID"; +const receiverId = "MESSAGE_RECEIVER_GUID"; +const receiverType = "group"; +const senderId = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -345,10 +377,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -356,10 +388,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId); ``` @@ -412,10 +444,10 @@ CometChat.markAsRead( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_SENDER_UID"; -var receiverType: string = "user"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_SENDER_UID"; +const receiverType: string = "user"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as read success."); @@ -430,10 +462,10 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( ```typescript -var messageId: string = "MESSAGE_ID"; -var receiverId: string = "MESSAGE_RECEIVER_GUID"; -var receiverType: string = "group"; -var senderId: string = "MESSAGE_SENDER_UID"; +const messageId: string = "MESSAGE_ID"; +const receiverId: string = "MESSAGE_RECEIVER_GUID"; +const receiverType: string = "group"; +const senderId: string = "MESSAGE_SENDER_UID"; CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( () => { console.log("mark as read success."); @@ -516,8 +548,8 @@ This method will mark all messages in the conversation as read. ```javascript -var conversationWith = "USER_UID"; -var conversationType = "user"; +const conversationWith = "USER_UID"; +const conversationType = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { @@ -532,8 +564,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```javascript -var conversationWith = "GROUP_GUID"; -var conversationType = "group"; +const conversationWith = "GROUP_GUID"; +const conversationType = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response) => { @@ -548,8 +580,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "USER_UID"; -var conversationType: string = "user"; +const conversationWith: string = "USER_UID"; +const conversationType: string = "user"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { @@ -564,8 +596,8 @@ CometChat.markConversationAsRead(conversationWith, conversationType).then( ```typescript -var conversationWith: string = "GROUP_GUID"; -var conversationType: string = "group"; +const conversationWith: string = "GROUP_GUID"; +const conversationType: string = "group"; CometChat.markConversationAsRead(conversationWith, conversationType).then( (response: string) => { @@ -791,3 +823,45 @@ The following features will be available only if the **Enhanced Messaging Status * `markMessageAsUnread` method. + + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + + +- **Mark as delivered on fetch**: Call `markAsDelivered()` when messages are fetched and displayed +- **Mark as read on view**: Call `markAsRead()` when the user actually views/scrolls to a message +- **Use message objects**: Prefer passing the full message object to `markAsDelivered()`/`markAsRead()` for simplicity +- **Batch receipts**: Mark the last message in a batch - all previous messages are automatically marked +- **Handle offline scenarios**: Receipts are queued and sent when the user comes back online + + + +- **Receipts not updating** — Verify `addMessageListener()` includes receipt handlers (`onMessagesDelivered`, `onMessagesRead`). +- **Double-tick not showing** — Call `markAsDelivered()` on message fetch and real-time receive. It won't happen automatically. +- **Read status not syncing** — Use the message object overload for `markAsRead()` for simpler implementation and fewer parameter errors. +- **Group receipts missing** — Enable "Enhanced Messaging Status" in the [CometChat Dashboard](https://app.cometchat.com) for group read receipts. + + +--- + +## Next Steps + + + + Show real-time typing status to users in conversations + + + Listen for incoming messages in real time + + + Fetch conversation list with unread counts + + + Complete reference for all SDK event listeners + + diff --git a/sdk/javascript/direct-call.mdx b/sdk/javascript/direct-call.mdx index 0bedb023..a72004fb 100644 --- a/sdk/javascript/direct-call.mdx +++ b/sdk/javascript/direct-call.mdx @@ -1,13 +1,41 @@ --- title: "Call Session" +description: "Learn how to generate call tokens, start and manage call sessions, configure call settings, and handle call events using the CometChat JavaScript Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Generate call token +const callToken = await CometChatCalls.generateToken(sessionId, authToken); + +// Build call settings +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .setCallListener(callListener) + .build(); + +// Start call session +CometChatCalls.startSession(callToken.token, callSettings, htmlElement); + +// End call session +CometChatCalls.endSession(); +``` + + ## Overview This section demonstrates how to start a call session in a web application. Previously known as **Direct Calling**. Before you begin, we strongly recommend you read the [calling setup guide](/sdk/javascript/calling-setup). + +**Available via:** SDK | [UI Kits](/ui-kit/react/overview) + + If you want to implement a complete calling experience with ringing functionality (incoming/outgoing call UI), follow the [Ringing](/sdk/javascript/default-call) guide first. Once the call is accepted, return here to start the call session. @@ -695,14 +723,56 @@ CometChatCalls.switchToVideoCall(); Terminates the current call session and releases all media resources (camera, microphone, network connections). After calling this method, the call view should be closed. - + ```javascript CometChatCalls.endSession(); ``` - -```typescript -CometChatCalls.endSession(); -``` - + + +Always remove call event listeners when they're no longer needed (e.g., on component unmount or when the call screen is closed). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChatCalls.removeCallEventListener("UNIQUE_LISTENER_ID"); +``` + + +--- + + + + - **Generate tokens just-in-time** — Generate call tokens immediately before starting a session rather than caching them, as tokens may expire. + - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience and proper resource cleanup. + - **Clean up on session end** — Always call `CometChatCalls.endSession()` in both `onCallEnded` and `onCallEndButtonPressed` callbacks to release media resources. + - **Use unique listener IDs** — Use descriptive, unique listener IDs to prevent accidental overwrites and enable targeted removal. + - **Provide a container element** — Ensure the HTML element passed to `startSession()` exists in the DOM and has appropriate dimensions for the call UI. + + + - **Black video screen** — Check that the HTML container element has explicit width and height. The call UI needs dimensions to render properly. + - **Token generation fails** — Verify the auth token is valid and the user is logged in. Ensure the session ID is a non-empty string. + - **No audio/video after joining** — Check browser permissions for camera and microphone. The user must grant access when prompted. + - **onCallEnded not firing** — This event only fires for 1:1 calls with exactly 2 participants. For group calls, use `onUserLeft` to track participants. + - **Duplicate event callbacks** — Ensure you're not registering the same listener multiple times. Use unique listener IDs and remove listeners when done. + - **Session timeout unexpected** — The default idle timeout is 180 seconds. Use `setIdleTimeoutPeriod()` to customize or disable (set to 0) if needed. + + + +--- + +## Next Steps + + + + Implement calls with incoming/outgoing ringing UI + + + Record call sessions for playback + + + Customize the video layout and main video container + + + Retrieve and display call history + + diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index 8b91b4ae..6949d281 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -1,14 +1,34 @@ --- title: "Edit A Message" +description: "Learn how to edit text and custom messages, receive real-time edit events, and handle missed edit events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Edit a text message +const textMessage = new CometChat.TextMessage(receiverID, "Updated text", receiverType); +textMessage.setId(messageId); +await CometChat.editMessage(textMessage); + +// Listen for real-time edits +CometChat.addMessageListener("edits", new CometChat.MessageListener({ + onMessageEdited: (message) => console.log("Edited:", message) +})); +``` + While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: 1. Adding a listener to receive [real-time message edits](/sdk/javascript/edit-message#real-time-message-edit-events) when your app is running 2. Calling a method to retrieve [missed message edits](/sdk/javascript/edit-message#missed-message-edit-events) when your app was not running + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Edit a Message *In other words, as a sender, how do I edit a message?* @@ -103,6 +123,26 @@ CometChat.editMessage(textMessage).then( + +```javascript +try { + let receiverID = "RECEIVER_UID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let messageId = "MESSAGE_ID_OF_THE_MESSAGE_TO_BE_EDITED"; + let textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); + + textMessage.setId(messageId); + + const message = await CometChat.editMessage(textMessage); + console.log("Message Edited", message); +} catch (error) { + console.log("Message editing failed with error:", error); +} +``` + + + The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message. @@ -157,6 +197,14 @@ new CometChat.MessageListener({ + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Message Edit Events *In other words, as a recipient, how do I know when someone edited their message when my app was not running?* @@ -175,3 +223,22 @@ For the message edited event, in the `Action` object received, the following fie In order to edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + +--- + +## Next Steps + + + + Remove messages from conversations + + + Send text, media, and custom messages + + + Organize conversations with message threads + + + Listen for incoming messages in real time + + diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index 350149f5..486ed70f 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -1,11 +1,32 @@ --- title: "Flag Message" +description: "Learn how to flag inappropriate messages for moderation review using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Get available flag reasons +const reasons = await CometChat.getFlagReasons(); + +// Flag a message +await CometChat.flagMessage("MESSAGE_ID", { + reasonId: "spam", + remark: "Promotional content" +}); +``` + + ## Overview Flagging messages allows users to report inappropriate content to moderators or administrators. When a message is flagged, it appears in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Flagged Messages** for review. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | Dashboard + + For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. @@ -218,3 +239,22 @@ if (result.success) { showToast("Message reported successfully"); } ``` + +--- + +## Next Steps + + + + Automate content moderation with AI + + + Remove messages from conversations + + + Listen for incoming messages in real time + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/group-add-members.mdx b/sdk/javascript/group-add-members.mdx index 98170bf0..5ade863a 100644 --- a/sdk/javascript/group-add-members.mdx +++ b/sdk/javascript/group-add-members.mdx @@ -1,8 +1,31 @@ --- title: "Add Members To A Group" +description: "Learn how to add members to a group, receive real-time member added events, and handle missed events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Add members to a group +const members = [ + new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT) +]; +await CometChat.addMembersToGroup("GUID", members, []); + +// Listen for member added events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { } +})); +``` + + +You can add members to a group programmatically and listen for real-time events when members are added. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Add Members to Group @@ -74,7 +97,7 @@ To receive real-time events whenever a new member is added to a group, you need ```javascript -var listenerID = "UNIQUE_LISTENER_ID"; +const listenerID = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, @@ -95,7 +118,7 @@ CometChat.addGroupListener( ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID"; +const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addGroupListener( listenerID, @@ -121,6 +144,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Member Added to Group event in Message History *In other words, as a member of a group, how do I know when someone is added to the group when my app is not running?* @@ -133,3 +164,38 @@ For the group member added event, in the `Action` object received, the following 2. `actionOn` - User object containing the details of the user who was added to the group 3. `actionBy` - User object containing the details of the user who added the member to the group 4. `actionFor` - Group object containing the details of the group to which the member was added + + +- **Batch member additions** — Add multiple members in a single `addMembersToGroup()` call rather than calling it once per user. +- **Set appropriate scopes** — Assign `PARTICIPANT` by default. Only use `ADMIN` or `MODERATOR` when the user genuinely needs elevated permissions. +- **Handle partial failures** — The response array contains per-user results. Check each entry for `"success"` or an error message to handle failures gracefully. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Validate UIDs before adding** — Ensure the UIDs exist and are not already members to avoid unnecessary API calls and confusing error responses. + + + +- **"ERR_NOT_A_MEMBER" error** — Only admins or moderators can add members. Verify the logged-in user has the correct scope in the group. +- **Some members fail while others succeed** — `addMembersToGroup()` returns per-user results. Check the response object for individual error messages (e.g., user already a member, invalid UID). +- **`onMemberAddedToGroup` not firing** — Ensure the group listener is registered before the add operation. Also verify the listener ID is unique and not being overwritten. +- **Duplicate events received** — You likely have multiple listeners registered with different IDs. Remove old listeners before adding new ones. +- **Banned members can't be added** — A banned user must be unbanned first before they can be added back to the group. + + +--- + +## Next Steps + + + + Remove or ban members from a group + + + Promote or demote group members + + + Fetch the list of members in a group + + + Allow users to join public or password-protected groups + + diff --git a/sdk/javascript/group-change-member-scope.mdx b/sdk/javascript/group-change-member-scope.mdx index 422ae34b..ac661755 100644 --- a/sdk/javascript/group-change-member-scope.mdx +++ b/sdk/javascript/group-change-member-scope.mdx @@ -1,8 +1,28 @@ --- title: "Change Member Scope" +description: "Learn how to change group member roles (admin, moderator, participant) and receive real-time scope change events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Change member scope to admin +await CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); + +// Listen for scope change events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { } +})); +``` + + +You can change the role of a group member between admin, moderator, and participant. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Change Scope of a Group Member @@ -96,6 +116,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Scope Changed Events *In other words, as a member of a group, how do I know when someone's scope is changed when my app is not running?* @@ -110,3 +138,38 @@ For the group member scope changed event, in the `Action` object received, the f 4. `actionFor` - Group object containing the details of the group in which the member scope was changed 5. `oldScope` - The original scope of the member 6. `newScope` - The updated scope of the member + + +- **Only admins can change scope** — The logged-in user must be the group admin to change another member's scope. Moderators cannot change scopes. +- **Confirm before promoting** — Promoting a user to admin gives them full control over the group. Add a confirmation dialog in your UI. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Use scope constants** — Always use `CometChat.GROUP_MEMBER_SCOPE.ADMIN`, `CometChat.GROUP_MEMBER_SCOPE.MODERATOR`, or `CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT` instead of raw strings. +- **Update UI after scope change** — Refresh the member list or update the local state after a successful scope change to reflect the new role immediately. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only the group admin can change member scopes. Verify the logged-in user is the admin. +- **Cannot demote another admin** — Only the group owner can demote admins. Regular admins can only change scope of moderators and participants. +- **`onGroupMemberScopeChanged` not firing** — Ensure the group listener is registered before the scope change and the listener ID is unique. +- **Scope change succeeds but UI doesn't update** — The API call returns a boolean. You need to manually update your local member list or re-fetch members after the change. +- **Invalid scope value error** — Use the SDK constants (`CometChat.GROUP_MEMBER_SCOPE.ADMIN`, etc.) rather than raw strings like `"admin"`. + + +--- + +## Next Steps + + + + Transfer ownership of a group to another member + + + Remove or ban members from a group + + + Add new members to a group + + + Fetch the list of members in a group + + diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 7433686c..5528815a 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -1,8 +1,27 @@ --- title: "Ban Or Kick Member From A Group" +description: "Learn how to kick, ban, and unban group members, fetch banned member lists, and receive real-time events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Kick a member +await CometChat.kickGroupMember("GUID", "UID"); + +// Ban a member +await CometChat.banGroupMember("GUID", "UID"); + +// Unban a member +await CometChat.unbanGroupMember("GUID", "UID"); + +// Fetch banned members +const request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); +const bannedMembers = await request.fetchNext(); +``` + There are certain actions that can be performed on the group members: @@ -13,6 +32,10 @@ There are certain actions that can be performed on the group members: All the above actions can only be performed by the **Admin** or the **Moderator** of the group. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Kick a Group Member The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. @@ -20,8 +43,8 @@ The Admin or Moderator of a group can kick a member out of the group using the ` ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.kickGroupMember(GUID, UID).then( response => { @@ -68,8 +91,8 @@ The Admin or Moderator of the group can ban a member from the group using the `b ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.banGroupMember(GUID, UID).then( response => { @@ -116,8 +139,8 @@ Only Admin or Moderators of the group can unban a previously banned member from ```javascript -var GUID = "GUID"; -var UID = "UID"; +const GUID = "GUID"; +const UID = "UID"; CometChat.unbanGroupMember(GUID, UID).then( response => { @@ -329,6 +352,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Kicked/Banned Events *In other words, as a member of a group, how do I know when someone is banned/kicked when my app is not running?* @@ -355,3 +386,38 @@ For group member unbanned event, the details can be obtained using the below fie 2. `actionBy` - User object containing the details of the user who has unbanned the member 3. `actionOn` - User object containing the details of the member that has been unbanned 4. `actionFor` - Group object containing the details of the Group from which the member was unbanned + + +- **Kick vs. Ban** — Use kick when you want the user to be able to rejoin. Use ban when the user should be permanently removed until explicitly unbanned. +- **Confirm before banning** — Banning is a stronger action than kicking. Add a confirmation dialog in your UI before calling `banGroupMember()`. +- **Remove listeners on cleanup** — Always call `CometChat.removeGroupListener()` when the component unmounts or the page navigates away. +- **Paginate banned members** — Use `BannedMembersRequestBuilder` with a reasonable limit (10–30) and call `fetchNext()` in a loop for large banned lists. +- **Handle permissions gracefully** — Only admins and moderators can kick/ban. Check the user's scope before showing these actions in the UI. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only admins or moderators can kick/ban members. Verify the logged-in user's scope in the group. +- **Kicked user can still see the group** — Kicking removes the user but doesn't prevent rejoining. If you need to block access, use `banGroupMember()` instead. +- **Banned user can rejoin** — This shouldn't happen. Verify you called `banGroupMember()` and not `kickGroupMember()`. Check the banned members list to confirm. +- **`onGroupMemberBanned` not firing** — Ensure the group listener is registered before the ban operation and the listener ID is unique. +- **Unban fails with error** — Verify the user is actually banned in the group. You can confirm by fetching the banned members list first. + + +--- + +## Next Steps + + + + Add new members to a group + + + Promote or demote group members + + + Fetch the list of members in a group + + + Allow members to leave a group + + diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index 4f3d1c36..07714742 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -1,10 +1,44 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Overview of group management in the CometChat JavaScript SDK including group types, member roles, and available operations." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Choose your path: +- **Create a Group** → [Create Group](/sdk/javascript/create-group) +- **Join a Group** → [Join Group](/sdk/javascript/join-group) +- **Retrieve Groups** → [Retrieve Groups](/sdk/javascript/retrieve-groups) +- **Manage Members** → [Add](/sdk/javascript/group-add-members) | [Kick/Ban](/sdk/javascript/group-kick-ban-members) | [Change Scope](/sdk/javascript/group-change-member-scope) +- **Update/Delete** → [Update Group](/sdk/javascript/update-group) | [Delete Group](/sdk/javascript/delete-group) + Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. Each group includes three kinds of users- owner, moderator, member. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Join existing groups as a participant + + + Fetch and filter the list of groups + + + Get the member list for a group + + diff --git a/sdk/javascript/interactive-messages.mdx b/sdk/javascript/interactive-messages.mdx index 2f083f73..99fefb19 100644 --- a/sdk/javascript/interactive-messages.mdx +++ b/sdk/javascript/interactive-messages.mdx @@ -1,11 +1,33 @@ --- title: "Interactive Messages" +description: "Learn how to send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send an interactive message +const interactiveMessage = new CometChat.InteractiveMessage( + receiverId, receiverType, "form", interactiveData +); +await CometChat.sendInteractiveMessage(interactiveMessage); + +// Listen for interactive messages +CometChat.addMessageListener("interactive", new CometChat.MessageListener({ + onInteractiveMessageReceived: (message) => { }, + onInteractionGoalCompleted: (receipt) => { } +})); +``` + An InteractiveMessage is a specialised object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## InteractiveMessage `InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: @@ -198,6 +220,33 @@ CometChat.addMessageListener( These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. + +Always remove message listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_ID"); +``` + + ## Usage An InteractiveMessage is constructed with the receiver's UID, the receiver type, the interactive type, and interactive data as a JSONObject. Once created, the InteractiveMessage can be sent using CometChat's sendInteractiveMessage() method. Incoming InteractiveMessages can be received and processed via CometChat's message listener framework. + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Send ephemeral messages that aren't stored + + + Understand message types and hierarchy + + diff --git a/sdk/javascript/join-group.mdx b/sdk/javascript/join-group.mdx index 744f9e72..6c8e688e 100644 --- a/sdk/javascript/join-group.mdx +++ b/sdk/javascript/join-group.mdx @@ -1,8 +1,31 @@ --- title: "Join A Group" +description: "Learn how to join public, password-protected, and private groups, and receive real-time join events using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Join a public group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PUBLIC, ""); + +// Join a password-protected group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PASSWORD, "password123"); + +// Listen for member joined events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberJoined: (message, joinedUser, joinedGroup) => { } +})); +``` + + +You can join groups to start participating in group conversations and receive real-time events when other members join. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Join a Group @@ -11,9 +34,9 @@ In order to start participating in group conversations, you will have to join a ```javascript -var GUID = "GUID"; -var password = ""; -var groupType = CometChat.GROUP_TYPE.PUBLIC; +const GUID = "GUID"; +const password = ""; +const groupType = CometChat.GROUP_TYPE.PUBLIC; CometChat.joinGroup(GUID, groupType, password).then( group => { @@ -28,7 +51,7 @@ group => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.joinGroup(GUID, CometChat.GroupType.Public).then( (group: CometChat.Group) => { @@ -94,6 +117,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTNER_ID"); +``` + + ## Missed Group Member Joined Events *In other words, as a member of a group, how do I know if someone joins the group when my app is not running?* @@ -105,3 +136,41 @@ For the group member joined event, in the `Action` object received, the followin 1. `action` - `joined` 2. `actionBy` - User object containing the details of the user who joined the group 3. `actionFor`- Group object containing the details of the group the user has joined + +--- + + + + - **Check `hasJoined` first** — Before calling `joinGroup()`, check the group's `hasJoined` property to avoid unnecessary API calls. + - **Handle password groups** — For password-protected groups, prompt the user for the password before calling `joinGroup()`. + - **Update UI on join** — After successfully joining, update your group list and enable messaging for that group. + - **Listen for join events** — Register `GroupListener` to receive real-time notifications when other members join. + - **Clean up listeners** — Remove group listeners when leaving the screen or component to prevent memory leaks. + + + - **"Already a member" error** — The user has already joined this group. Check `hasJoined` before attempting to join. + - **"Invalid password" error** — The password provided doesn't match. Ensure the password is correct for password-protected groups. + - **Can't join private group** — Private groups require an invitation. Users must be added by an admin using `addMembersToGroup()`. + - **Join events not received** — Ensure `addGroupListener()` is called before the join event occurs. Verify the listener ID is unique. + - **Group not found** — The GUID may be incorrect or the group may have been deleted. Verify the GUID exists. + + + +--- + +## Next Steps + + + + Allow members to leave a group + + + Fetch the list of members in a group + + + Send messages to group conversations + + + Programmatically add members to a group + + diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index 37e5885f..dcb2b1c3 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -1,8 +1,23 @@ --- title: "Key Concepts" +description: "Understand the core concepts of CometChat including users, groups, messaging categories, authentication, and member roles." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Key identifiers: +- **UID** — Unique User Identifier (alphanumeric, underscore, hyphen) +- **GUID** — Group Unique Identifier (alphanumeric, underscore, hyphen) +- **Auth Key** — Development-only credential for quick testing +- **Auth Token** — Secure per-user token for production use +- **REST API Key** — Server-side credential, never expose in client code + +Group types: `Public` | `Password` | `Private` +Member scopes: `Admin` | `Moderator` | `Participant` +Message categories: `message` | `custom` | `action` | `call` + ### CometChat Dashboard @@ -125,3 +140,42 @@ Any message in CometChat can belong to either one of the below categories | call | These are call-related messages. These can belong to either one of the two types: 1. audio 2. video | For more information, you can refer to the [Message structure and hierarchy guide](/sdk/javascript/message-structure-and-hierarchy). + +### Glossary Quick Lookup + +| Term | Definition | Learn More | +| --- | --- | --- | +| UID | Unique User Identifier — alphanumeric string you assign to each user | [Users Overview](/sdk/javascript/users-overview) | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | [Groups Overview](/sdk/javascript/groups-overview) | +| Auth Key | Development-only credential for quick testing. Never use in production | [Authentication](/sdk/javascript/authentication-overview) | +| Auth Token | Secure, per-user token generated via REST API. Use in production | [Authentication](/sdk/javascript/authentication-overview#login-using-auth-token) | +| REST API Key | Server-side credential for REST API calls. Never expose in client code | [CometChat Dashboard](https://app.cometchat.com) | +| Receiver Type | Specifies if a message target is a `user` or `group` | [Send Message](/sdk/javascript/send-message) | +| Scope | Group member scope: `admin`, `moderator`, or `participant` | [Change Member Scope](/sdk/javascript/group-change-member-scope) | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) | +| Conversation | A chat thread between two users or within a group | [Retrieve Conversations](/sdk/javascript/retrieve-conversations) | +| Metadata | Custom JSON data attached to users, groups, or messages | [Send Message](/sdk/javascript/send-message) | +| Tags | String labels for categorizing users, groups, conversations, or messages | [Additional Filtering](/sdk/javascript/additional-message-filtering) | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | [Additional Filtering](/sdk/javascript/additional-message-filtering) | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | [Setup SDK](/sdk/javascript/setup-sdk) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | [Transient Messages](/sdk/javascript/transient-messages) | +| Interactive Message | Message with actionable UI elements (forms, cards, buttons) | [Interactive Messages](/sdk/javascript/interactive-messages) | + +--- + +## Next Steps + + + + Install and initialize the CometChat SDK + + + Log users in and manage auth tokens + + + Send your first text or media message + + + Create and manage group conversations + + diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index a9534b8a..7bcb9581 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -1,8 +1,28 @@ --- title: "Leave A Group" +description: "Learn how to leave a group and receive real-time events when members leave using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Leave a group +await CometChat.leaveGroup("GUID"); + +// Listen for member left events +CometChat.addGroupListener("listener", new CometChat.GroupListener({ + onGroupMemberLeft: (message, leavingUser, group) => { } +})); +``` + + +You can leave a group to stop receiving updates and messages from that group conversation. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Leave a Group @@ -11,7 +31,7 @@ In order to stop receiving updates and messages for any particular joined group, ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.leaveGroup(GUID).then( hasLeft => { @@ -26,7 +46,7 @@ hasLeft => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.leaveGroup(GUID).then( (hasLeft: boolean) => { @@ -84,6 +104,14 @@ CometChat.addGroupListener( + +Always remove group listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Left Events *In other words, as a member of a group, how do I know if someone has left it when my app is not running?* @@ -95,3 +123,41 @@ For the group member left event, in the `Action` object received, the following 1. `action` - `left` 2. `actionBy` - User object containing the details of the user who left the group 3. `actionFor` - Group object containing the details of the group the user has left + +--- + + + + - **Confirm before leaving** — Show a confirmation dialog before leaving a group, especially for groups with important conversations. + - **Update UI immediately** — Remove the group from the active list and disable messaging after successfully leaving. + - **Handle owner leaving** — If the group owner leaves, ownership should be transferred first using [Transfer Group Ownership](/sdk/javascript/transfer-group-ownership). + - **Clean up listeners** — Remove any group-specific listeners after leaving to prevent memory leaks and stale event handling. + - **Check missed events** — When re-joining a group, fetch missed messages and action events to stay up to date. + + + - **"Not a member" error** — The user is not a member of this group. Verify the GUID and check `hasJoined` status. + - **Owner can't leave** — Group owners must transfer ownership before leaving. Use `transferGroupOwnership()` first. + - **Leave events not received** — Ensure `addGroupListener()` is registered before the leave event occurs. Check listener IDs are unique. + - **Still receiving group messages** — Ensure `leaveGroup()` completed successfully. Check the promise resolved without errors. + - **Group still in conversation list** — Refresh the conversation list after leaving. The group may still appear until the list is re-fetched. + + + +--- + +## Next Steps + + + + Join public or password-protected groups + + + Permanently delete a group + + + Remove or ban members from a group + + + Fetch and filter the list of groups + + diff --git a/sdk/javascript/login-listener.mdx b/sdk/javascript/login-listener.mdx index 4c98ff4c..b58b9dd9 100644 --- a/sdk/javascript/login-listener.mdx +++ b/sdk/javascript/login-listener.mdx @@ -1,8 +1,25 @@ --- title: "Login Listener" +description: "Listen for real-time login and logout events using the CometChat JavaScript SDK LoginListener class." --- - +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Add login listener +CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({ + loginSuccess: (user) => { }, + loginFailure: (error) => { }, + logoutSuccess: () => { }, + logoutFailure: (error) => { } +})); + +// Remove login listener +CometChat.removeLoginListener("LISTENER_ID"); +``` + The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class provided. LoginListener consists of 4 events that can be triggered. These are as follows: @@ -42,7 +59,7 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov ```typescript - var listenerID: string = "UNIQUE_LISTENER_ID"; + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addLoginListener( listenerID, new CometChat.LoginListener({ @@ -66,12 +83,86 @@ To add the `LoginListener`, you need to use the `addLoginListener()` method prov +### React Example + +If you're using React, register the listener inside a `useEffect` hook and clean it up on unmount: + + + +```javascript +import { useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function useLoginListener() { + useEffect(() => { + const listenerID = "LOGIN_LISTENER"; + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user) => { + console.log("User logged in:", user); + }, + loginFailure: (error) => { + console.log("Login failed:", error); + }, + logoutSuccess: () => { + console.log("User logged out"); + // Redirect to login page, clear app state, etc. + }, + logoutFailure: (error) => { + console.log("Logout failed:", error); + }, + }) + ); + + return () => { + CometChat.removeLoginListener(listenerID); + }; + }, []); +} +``` + + +```typescript +import { useEffect } from "react"; +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +function useLoginListener(): void { + useEffect(() => { + const listenerID: string = "LOGIN_LISTENER"; + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user: CometChat.User) => { + console.log("User logged in:", user); + }, + loginFailure: (error: CometChat.CometChatException) => { + console.log("Login failed:", error); + }, + logoutSuccess: () => { + console.log("User logged out"); + }, + logoutFailure: (error: CometChat.CometChatException) => { + console.log("Logout failed:", error); + }, + }) + ); + + return () => { + CometChat.removeLoginListener(listenerID); + }; + }, []); +} +``` + + + In order to stop receiving events related to login and logout you need to use the removeLoginListener() method provided by the SDK and pass the ID of the listener that needs to be removed. ```js - var listenerID = "UNIQUE_LISTENER_ID"; + const listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` @@ -79,10 +170,47 @@ In order to stop receiving events related to login and logout you need to use th ```typescript - var listenerID: string = "UNIQUE_LISTENER_ID"; + const listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeLoginListener(listenerID); ``` + + +Always remove login listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + +## Best Practices + + + + Each listener must have a unique ID string. If you register a new listener with the same ID, it will replace the previous one. Use descriptive IDs like `"LOGIN_LISTENER_MAIN"` or `"LOGIN_LISTENER_AUTH_SCREEN"` to avoid accidental overwrites. + + + Use the `logoutSuccess` callback to clear your app's local state, redirect to the login screen, and clean up any other SDK listeners. This ensures a clean state when the user logs out. + + + Register login listeners as early as possible in your app lifecycle (e.g., right after `init()`). Remove them only when the component or page that registered them is destroyed. + + + +--- + +## Next Steps + + + + Learn about login methods and auth tokens + + + Monitor the SDK connection state in real time + + + Complete reference for all SDK event listeners + + + Manually manage WebSocket connections + + diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index 90cf107b..38189663 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -1,8 +1,25 @@ --- title: "Managing Web Sockets Connections Manually" +description: "Learn how to manually manage WebSocket connections for real-time messaging using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Disable auto WebSocket connection during init +const appSettings = new CometChat.AppSettingsBuilder() + .setRegion("REGION") + .autoEstablishSocketConnection(false) + .build(); +await CometChat.init("APP_ID", appSettings); + +// Manually connect/disconnect +CometChat.connect(); +CometChat.disconnect(); +``` + ## Default SDK behaviour on login @@ -98,3 +115,38 @@ CometChat.disconnect(); + + +- **Only disable auto-connect when needed** — The default auto-connect behavior works well for most apps. Only manage connections manually if you need fine-grained control (e.g., background/foreground transitions, battery optimization). +- **Check login status before connecting** — Always verify the user is logged in with `CometChat.getLoggedInUser()` before calling `CometChat.connect()`. +- **Pair with Connection Listener** — Use `CometChat.addConnectionListener()` alongside manual connection management to track the actual connection state. +- **Reconnect on app foreground** — If you disconnect when the app goes to background, call `CometChat.connect()` when the app returns to foreground. +- **Don't call connect/disconnect rapidly** — Allow time for the connection to establish or close before toggling again. + + + +- **No real-time events after login** — If you set `autoEstablishSocketConnection(false)`, you must call `CometChat.connect()` manually after login. +- **`connect()` doesn't seem to work** — Ensure the user is logged in first. `connect()` requires an authenticated session. +- **Events stop after calling `disconnect()`** — This is expected. Call `CometChat.connect()` to resume receiving events. +- **Connection drops intermittently** — This is usually a network issue. The SDK auto-reconnects by default, but if you're managing connections manually, you need to handle reconnection logic yourself. +- **`autoEstablishSocketConnection(false)` not taking effect** — Make sure you're passing it to the `AppSettingsBuilder` before calling `CometChat.init()`. It cannot be changed after initialization. + + +--- + +## Next Steps + + + + Monitor the SDK connection state in real time + + + Listen for login and logout events + + + Complete reference for all SDK event listeners + + + SDK installation and initialization guide + + diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index c3ce4742..a94cef3a 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -1,13 +1,38 @@ --- title: "Mentions" +description: "Learn how to send messages with user mentions, retrieve mentioned users, and filter messages by mention metadata using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Send a message with a mention (use <@uid:UID> format) +const msg = new CometChat.TextMessage("receiverUID", "Hello <@uid:cometchat-uid-1>", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(msg); + +// Get mentioned users from a message +const mentionedUsers = message.getMentionedUsers(); + +// Fetch messages with mention tag info +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).mentionsWithTagInfo(true).build(); +const messages = await request.fetchPrevious(); +``` + + + Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user’s unique identification. Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send Mentioned Messages To send a message with a mentioned user, you must follow a specific format: `<@uid:UID>`. For example, to mention the user with UID `cometchat-uid-1` with the message "`Hello`," your text would be `"Hello, <@uid:cometchat-uid-1>"` @@ -127,7 +152,7 @@ To get a list of messages in a conversation where users are mentioned along with let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) .mentionsWithTagInfo(true) @@ -154,7 +179,7 @@ messagesRequest.fetchPrevious().then( let GUID = "GUID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .mentionsWithTagInfo(true) @@ -246,7 +271,7 @@ To get a list of messages in a conversation where users are mentioned along with let UID = "UID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) .mentionsWithBlockedInfo(true) @@ -274,7 +299,7 @@ messagesRequest.fetchPrevious().then( let GUID = "GUID"; let limit = 30; -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .mentionsWithBlockedInfo(true) @@ -366,3 +391,37 @@ To retrieve the list of users mentioned in the particular message, you can use t ```javascript message.getMentionedUsers() ``` + + +- **Use correct format**: Always use `<@uid:UID>` format for mentions in message text +- **Validate UIDs**: Ensure mentioned UIDs exist before sending +- **Highlight mentions in UI**: Parse message text and style mentions differently +- **Fetch tag info when needed**: Use `mentionsWithTagInfo(true)` to get user tags for mentioned users +- **Handle blocked users**: Use `mentionsWithBlockedInfo(true)` to check blocked relationships + + + +- **Mention not parsed** — Use the `<@uid:UID>` format exactly. Any deviation will prevent parsing. +- **`getMentionedUsers()` returns empty** — This only works on messages received from the server, not locally constructed messages. +- **Missing user tags** — Add `mentionsWithTagInfo(true)` to your request builder to include tag information. +- **Blocked info missing** — Add `mentionsWithBlockedInfo(true)` to your request builder to include blocked relationship data. + + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Add emoji reactions to messages + + + Organize conversations with message threads + + diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 797cb91d..38970797 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -1,9 +1,20 @@ --- title: "Message" sidebarTitle: "Message Structure And Hierarchy" +description: "Understand the message categories, types, and hierarchy in the CometChat JavaScript SDK including text, media, custom, action, interactive, and call messages." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Message categories and types: +- **message** → `text`, `image`, `video`, `audio`, `file` +- **custom** → Developer-defined types (e.g., `location`, `poll`) +- **interactive** → `form`, `card`, `customInteractive` +- **action** → `groupMember` (joined/left/kicked/banned), `message` (edited/deleted) +- **call** → `audio`, `video` + The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. @@ -11,6 +22,74 @@ The below diagram helps you better understand the various message categories and +### Checking Message Category and Type + +You can determine the category and type of any received message using the following methods: + + + +```javascript +// Check message category +const category = message.getCategory(); // "message", "custom", "action", "call", "interactive" + +// Check message type +const type = message.getType(); // "text", "image", "video", "audio", "file", etc. + +// Example: Handle different message categories +switch (category) { + case CometChat.CATEGORY_MESSAGE: + if (type === CometChat.MESSAGE_TYPE.TEXT) { + console.log("Text message:", message.getText()); + } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { + console.log("Image URL:", message.getData().url); + } + break; + case CometChat.CATEGORY_CUSTOM: + console.log("Custom message type:", type, "data:", message.getData()); + break; + case CometChat.CATEGORY_ACTION: + console.log("Action:", message.getAction()); + break; + case CometChat.CATEGORY_CALL: + console.log("Call status:", message.getStatus()); + break; +} +``` + + +```typescript +// Check message category +const category: string = message.getCategory(); +const type: string = message.getType(); + +// Example: Handle different message categories +switch (category) { + case CometChat.CATEGORY_MESSAGE: + if (type === CometChat.MESSAGE_TYPE.TEXT) { + const textMsg = message as CometChat.TextMessage; + console.log("Text message:", textMsg.getText()); + } else if (type === CometChat.MESSAGE_TYPE.IMAGE) { + const mediaMsg = message as CometChat.MediaMessage; + console.log("Image URL:", mediaMsg.getData().url); + } + break; + case CometChat.CATEGORY_CUSTOM: + const customMsg = message as CometChat.CustomMessage; + console.log("Custom message type:", type, "data:", customMsg.getData()); + break; + case CometChat.CATEGORY_ACTION: + const actionMsg = message as CometChat.Action; + console.log("Action:", actionMsg.getAction()); + break; + case CometChat.CATEGORY_CALL: + const callMsg = message as CometChat.Call; + console.log("Call status:", callMsg.getStatus()); + break; +} +``` + + + As you can see in the above diagram, every message belongs to a particular category. A message can belong to either one of the 4 categories 1. Message @@ -32,6 +111,8 @@ A message belonging to the category `message` can be classified into either 1 of In the case of messages that belong to the `custom` category, there are no predefined types. Custom messages can be used by developers to send messages that do not fit in the default category and types provided by CometChat. For messages with the category `custom`, the developers can set their own type to uniquely identify the custom message. A very good example of a custom message would be the sharing of location co-ordinates. In this case, the developer can decide to use the custom message with type set to `location`. +For sending custom messages, see [Send Message → Custom Messages](/sdk/javascript/send-message#custom-message). + ## Interactive An InteractiveMessage is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. Messages belonging to the interactive category can further be classified into one of the below types: @@ -75,6 +156,8 @@ Messages with the category `call` are Calling related messages. These can belong 1. audio 2. video +For implementing calling, see [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call). + The call messages have a property called status that helps you figure out the status of the call. The status can be either one of the below values: 1. initiated - when a is initiated to a user/group @@ -84,3 +167,22 @@ The call messages have a property called status that helps you figure out the st 5. unanswered - when the call was not answered by the receiver. 6. busy - when the receiver of the call was busy on another call. 7. ended - when the call was successfully completed and ended by either the initiator or receiver. + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Send messages with embedded forms and buttons + + + Advanced message filtering with RequestBuilder + + diff --git a/sdk/javascript/messaging-overview.mdx b/sdk/javascript/messaging-overview.mdx index 5a8902b4..bb3a05a9 100644 --- a/sdk/javascript/messaging-overview.mdx +++ b/sdk/javascript/messaging-overview.mdx @@ -1,12 +1,41 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Overview of messaging capabilities in the CometChat JavaScript SDK including sending, receiving, editing, deleting messages, and advanced features." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +Choose your path: +- **Send Messages** → [Send Message](/sdk/javascript/send-message) - Text, media, custom +- **Receive Messages** → [Receive Message](/sdk/javascript/receive-message) - Real-time listeners +- **Edit/Delete** → [Edit](/sdk/javascript/edit-message) | [Delete](/sdk/javascript/delete-message) +- **Advanced** → [Threads](/sdk/javascript/threaded-messages) | [Reactions](/sdk/javascript/reactions) | [Mentions](/sdk/javascript/mentions) + Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. At the minimum, you must add code for [sending messages](/sdk/javascript/send-message) and [receiving messages](/sdk/javascript/receive-message). Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/javascript/typing-indicators) and [delivery & read receipts](/sdk/javascript/delivery-read-receipts). + +--- + +## Next Steps + + + + Send text, media, and custom messages + + + Listen for incoming messages in real time + + + Understand message categories and types + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index f7edcaaa..2c025e64 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -1,8 +1,30 @@ --- title: "Overview" +description: "Get started with the CometChat JavaScript SDK — install, initialize, create users, log in, and integrate UI Kits or Chat Widget." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +# Install +npm install @cometchat/chat-sdk-javascript +``` + +```javascript +// Initialize (run once at app start) +const appSettings = new CometChat.AppSettingsBuilder().setRegion("REGION").subscribePresenceForAllUsers().build(); +await CometChat.init("APP_ID", appSettings); + +// Login +await CometChat.login("UID", "AUTH_KEY"); // Dev only +await CometChat.login(AUTH_TOKEN); // Production +``` + +**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + This guide demonstrates how to add chat to a JavaScript application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/javascript/key-concepts) guide. @@ -77,6 +99,10 @@ Include the CometChat JavaScript library in your HTML code ### Server Side Rendering (SSR) Compatibility + +**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the examples below. + + You can use CometChat with SSR frameworks such as [Next.js](https://nextjs.org/) or [NuxtJS](https://nuxtjs.org/) by importing it dynamically on the client side. #### Next.js @@ -352,10 +378,39 @@ CometChat.init(appID, appSetting).then( + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .setStorageMode(CometChat.StorageMode.SESSION) + .build(); + +try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); +} catch (error) { + console.log("Initialization failed with error:", error); +} +``` + + + Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + + + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + ## Register and Login your user Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. @@ -363,11 +418,11 @@ Once initialization is successful, you will need to create a user. To create use ```js -let authKey = "AUTH_KEY"; -var UID = "user1"; -var name = "Kevin"; +const authKey = "AUTH_KEY"; +const UID = "user1"; +const name = "Kevin"; -var user = new CometChat.User(UID); +const user = new CometChat.User(UID); user.setName(name); @@ -389,7 +444,7 @@ let authKey: string = "AUTH_KEY", UID: string = "user1", name: string = "Kevin"; -var user = new CometChat.User(UID); +const user = new CometChat.User(UID); user.setName(name); @@ -405,6 +460,25 @@ CometChat.createUser(user, authKey).then( + +```javascript +const authKey = "AUTH_KEY"; +const UID = "user1"; +const name = "Kevin"; + +const user = new CometChat.User(UID); +user.setName(name); + +try { + const createdUser = await CometChat.createUser(user, authKey); + console.log("user created", createdUser); +} catch (error) { + console.log("error", error); +} +``` + + + Make sure that `UID` and `name` are specified as these are mandatory fields to create a user. @@ -422,8 +496,8 @@ This straightforward authentication method is ideal for proof-of-concept (POC) d ```js -var UID = "cometchat-uid-1"; -var authKey = "AUTH_KEY"; +const UID = "cometchat-uid-1"; +const authKey = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user) => { @@ -448,8 +522,8 @@ CometChat.getLoggedinUser().then( ```typescript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; +const UID: string = "cometchat-uid-1"; +const authKey: string = "AUTH_KEY"; CometChat.getLoggedinUser().then( (user: CometChat.User) => { @@ -472,6 +546,24 @@ CometChat.getLoggedinUser().then( + +```javascript +const UID = "cometchat-uid-1"; +const authKey = "AUTH_KEY"; + +try { + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + const user = await CometChat.login(UID, authKey); + console.log("Login Successful:", { user }); + } +} catch (error) { + console.log("Login failed with exception:", { error }); +} +``` + + + Make sure you replace the `AUTH_KEY` with your CometChat **AuthKey** in the above code. @@ -500,3 +592,22 @@ UID can be alphanumeric with an underscore and hyphen. Spaces, punctuation and o ## Integrate our Chat Widget * Please refer to the section to integrate [Chat Widget](/widget/html-bootstrap-jquery) into your Website. + +--- + +## Next Steps + + + + Understand UIDs, GUIDs, auth tokens, and more + + + Learn about login methods and auth token generation + + + Send your first text or media message + + + Listen for incoming messages in real time + + diff --git a/sdk/javascript/presenter-mode.mdx b/sdk/javascript/presenter-mode.mdx index 42b2bdc2..d7f94aa3 100644 --- a/sdk/javascript/presenter-mode.mdx +++ b/sdk/javascript/presenter-mode.mdx @@ -1,8 +1,26 @@ --- title: "Presenter Mode" +description: "Learn how to implement Presenter Mode for webinars, keynotes, and online classes using the CometChat JavaScript Calls SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start a presentation session +const settings = new CometChatCalls.PresenterSettingsBuilder() + .setIsPresenter(true) + .enableDefaultLayout(true) + .setCallEventListener(callListener) + .build(); + +CometChatCalls.joinPresentation(callToken, settings, htmlElement); +``` + +- **Presenter** (max 5): Can share video, audio, and screen +- **Viewer** (up to 100 total): Passive consumers, no outgoing streams + ## Overview @@ -145,3 +163,46 @@ The options available for customization of calls are: In case you wish to achieve a completely customised UI for the Calling experience, you can do so by embedding default android buttons to the screen as per your requirement and then use the below methods to achieve different functionalities for the embedded buttons. For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat you can embed the buttons in your layout and use the below methods to perform the corresponding operations: + + +Always remove call event listeners when they're no longer needed (e.g., on component unmount or when the presentation screen is closed). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChatCalls.removeCallEventListener("UNIQUE_ID"); +``` + + + +- **Generate a fresh call token** — Always generate a new call token using `generateToken()` before starting a presentation. Reusing expired tokens will fail. +- **Set presenter role explicitly** — Use `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. The default is viewer. +- **Limit presenters to 5** — The maximum number of presenters is 5. Additional users should join as viewers. +- **Remove listeners on cleanup** — Always call `CometChatCalls.removeCallEventListener()` when the component unmounts or the presentation ends. +- **Handle `onCallEnded` and `onCallEndButtonPressed`** — These are different events. `onCallEnded` fires when the call ends server-side, while `onCallEndButtonPressed` fires when the user clicks the end button locally. + + + +- **Presentation doesn't start** — Ensure you've generated a valid call token and the HTML element exists in the DOM before calling `joinPresentation()`. +- **Viewer can send audio/video** — Verify `setIsPresenter(false)` is set for viewers. Viewers should not have outgoing streams. +- **`onUserJoined` not firing** — Ensure the call event listener is registered before joining the presentation. +- **Black screen after joining** — Check that the HTML element passed to `joinPresentation()` is visible and has proper dimensions (width/height). +- **More than 5 presenters needed** — Presenter Mode supports a maximum of 5 presenters. Consider using a standard group call for more active participants. + + +--- + +## Next Steps + + + + Start standard call sessions without presenter mode + + + Record call and presentation sessions + + + Add virtual backgrounds to video calls + + + Customize the video layout and containers + + diff --git a/sdk/javascript/rate-limits.mdx b/sdk/javascript/rate-limits.mdx index 17581b14..9c970fd4 100644 --- a/sdk/javascript/rate-limits.mdx +++ b/sdk/javascript/rate-limits.mdx @@ -1,8 +1,17 @@ --- title: "Rate Limits" +description: "Understand CometChat REST API rate limits, response headers, and how to handle rate-limited requests in your JavaScript application." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- Core Operations (login, create/delete user, create/join group): `10,000` requests/min cumulative +- Standard Operations (all other): `20,000` requests/min cumulative +- Rate-limited responses return HTTP `429` with `Retry-After` and `X-Rate-Limit-Reset` headers +- Monitor usage via `X-Rate-Limit` and `X-Rate-Limit-Remaining` response headers + ### CometChat REST API Rate Limits @@ -32,3 +41,86 @@ However, we do provide the following response headers that you can use to confir `X-Rate-Limit: 700` `X-Rate-Limit-Remaining: 699` + +## Handling Rate-Limited Responses + +When your application receives a `429` response, you should wait before retrying. Here's a recommended approach using exponential backoff: + + + +```javascript +async function callWithRetry(apiCall, maxRetries = 3) { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (error) { + if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + const waitTime = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s + console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); + await new Promise((resolve) => setTimeout(resolve, waitTime)); + } else { + throw error; + } + } + } +} + +// Usage +const users = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); +``` + + +```typescript +async function callWithRetry(apiCall: () => Promise, maxRetries: number = 3): Promise { + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await apiCall(); + } catch (error: any) { + if (error.code === "ERR_TOO_MANY_REQUESTS" && attempt < maxRetries - 1) { + const waitTime = Math.pow(2, attempt) * 1000; + console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`); + await new Promise((resolve) => setTimeout(resolve, waitTime)); + } else { + throw error; + } + } + } + throw new Error("Max retries exceeded"); +} + +// Usage +const users: CometChat.User[] = await callWithRetry(() => + new CometChat.UsersRequestBuilder().setLimit(30).build().fetchNext() +); +``` + + + +## Best Practices + + + + If you need to perform many operations (e.g., sending messages to multiple users), space them out over time rather than firing them all at once. Use a queue or throttle mechanism to stay within the per-minute limits. + + + Check the `X-Rate-Limit-Remaining` header in REST API responses to proactively slow down before hitting the limit. This is more efficient than waiting for `429` errors. + + + Core operations (login, create/delete user, create/join group) share a lower cumulative limit of 10,000/min. Standard operations have a higher 20,000/min limit. Plan your architecture accordingly — avoid frequent login/logout cycles. + + + +--- + +## Next Steps + + + + Install and configure the CometChat JavaScript SDK + + + Learn the core concepts behind CometChat + + diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 8ac8f43f..7821dd0c 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -1,11 +1,38 @@ --- title: "Reactions" +description: "Add, remove, and fetch message reactions in real-time using the CometChat JavaScript SDK. Includes listener events and helper methods for updating UI." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Add a reaction +await CometChat.addReaction(messageId, "😊"); + +// Remove a reaction +await CometChat.removeReaction(messageId, "😊"); + +// Fetch reactions for a message +const request = new CometChat.ReactionRequestBuilder() + .setMessageId(messageId).setLimit(10).build(); +const reactions = await request.fetchNext(); + +// Listen for reaction events +CometChat.addMessageListener("LISTENER_ID", { + onMessageReactionAdded: (reaction) => {}, + onMessageReactionRemoved: (reaction) => {} +}); +``` + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Add a Reaction Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. @@ -201,6 +228,10 @@ reactionRequest.fetchPrevious().then( Keep the chat interactive with real-time updates for reactions. Register a listener for these events and make your UI responsive. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```js @@ -361,3 +392,31 @@ action After calling this method, the message instance's reactions are updated. You can then use message.getReactions() to get the latest reactions and refresh your UI accordingly. + + +- **Update UI optimistically**: Show the reaction immediately, then sync with server response +- **Use `updateMessageWithReactionInfo()`**: Keep message objects in sync with real-time events +- **Limit reaction options**: Provide a curated set of emojis for better UX +- **Show reaction counts**: Display aggregated counts with `getReactions()` for each message +- **Handle duplicates**: Check `getReactedByMe()` before allowing users to add the same reaction + + + +- **Reaction not appearing** — Call `updateMessageWithReactionInfo()` on real-time events to keep the UI in sync. +- **Duplicate reactions** — Use `getReactedByMe()` to check if the user already reacted before adding. +- **Reactions out of sync** — Ensure `onMessageReactionAdded` and `onMessageReactionRemoved` handlers are registered. +- **Can't remove reaction** — Use the exact same emoji string that was used when adding the reaction. + + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index a6f9a892..0b4d12f1 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1,20 +1,55 @@ --- title: "Receive A Message" +description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, search messages, and get unread counts using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Listen for real-time messages +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => {}, + onMediaMessageReceived: (msg) => {}, + onCustomMessageReceived: (msg) => {} +})); + +// Fetch missed messages (while app was offline) +const latestId = await CometChat.getLastDeliveredMessageId(); +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setMessageId(latestId).setLimit(30).build(); +const messages = await request.fetchNext(); + +// Fetch message history +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).build(); +const messages = await request.fetchPrevious(); + +// Get unread message count +const counts = await CometChat.getUnreadMessageCount(); +``` + Receiving messages with CometChat has two parts: 1. Adding a listener to receive [real-time messages](/sdk/javascript/receive-message#real-time-messages) when your app is running 2. Calling a method to retrieve [missed messages](/sdk/javascript/receive-message#missed-messages) when your app was not running + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Real-Time Messages *In other words, as a recipient, how do I receive messages when my app is running?* To receive real-time incoming messages, you need to register the `MessageListener` wherever you wish to receive the incoming messages. You can use the `addMessageListener()` method to do so. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```javascript @@ -116,7 +151,7 @@ let UID = "UID"; let limit = 30; let latestId = await CometChat.getLastDeliveredMessageId(); -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setMessageId(latestId) .setLimit(limit) @@ -169,7 +204,7 @@ let GUID = "GUID"; let limit = 30; let latestId = await CometChat.getLastDeliveredMessageId(); -var messagesRequest = new CometChat.MessagesRequestBuilder() +let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setMessageId(latestId) .setLimit(limit) @@ -956,3 +991,33 @@ CometChat.getUnreadMessageCountForAllGroups().then( It returns an object which will contain the GUID as the key and the unread message count as the value. + + +- **Remove listeners on cleanup**: Always call `removeMessageListener()` when components unmount to prevent memory leaks +- **Use unique listener IDs**: Generate unique IDs per component/screen to avoid conflicts +- **Handle all message types**: Implement handlers for text, media, and custom messages +- **Fetch missed messages on app resume**: Call `getLastDeliveredMessageId()` and fetch messages since that ID +- **Paginate message history**: Use `setLimit()` with reasonable values (30-50) and call `fetchPrevious()` for more +- **Filter by category/type**: Use `setCategories()` and `setTypes()` to fetch only relevant messages + + + +- **Not receiving messages** — Verify `addMessageListener()` was called with the correct listener ID before messages are sent. +- **Duplicate messages** — Ensure only one listener per ID is registered. Remove listeners on component unmount. +- **Missing messages after reconnect** — Use `getLastDeliveredMessageId()` + `fetchNext()` to fetch messages missed while offline. +- **Wrong message count** — Blocked users may be included. Use `hideMessagesFromBlockedUsers` parameter to exclude them. +- **History not loading** — Use `fetchPrevious()` for message history and `fetchNext()` for missed messages. Don't mix them up. + + +--- + +## Next Steps + + + + Track when messages are delivered and read by recipients + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/recording.mdx b/sdk/javascript/recording.mdx index 214d56bc..a7d57a68 100644 --- a/sdk/javascript/recording.mdx +++ b/sdk/javascript/recording.mdx @@ -1,11 +1,35 @@ --- title: "Recording (Beta)" +description: "Implement call recording for voice and video calls using the CometChat JavaScript SDK, including start/stop controls, listeners, and accessing recordings from the Dashboard." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start recording +CometChatCalls.startRecording(); + +// Stop recording +CometChatCalls.stopRecording(); + +// Listen for recording events (in CallSettings) +const callListener = new CometChatCalls.OngoingCallListener({ + onRecordingStarted: (event) => console.log("Recording started", event.user), + onRecordingStopped: (event) => console.log("Recording stopped", event.user), +}); +``` + +**Recordings are available on the [CometChat Dashboard](https://app.cometchat.com) → Calls section.** + This section will guide you to implement call recording feature for the voice and video calls. + +**Available via:** SDK | Dashboard + + ## Implementation Once you have decided to implement [Default Calling](/sdk/javascript/default-call) or [Direct Calling](/sdk/javascript/direct-call) calling and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. @@ -14,6 +38,10 @@ You need to make changes in the CometChat.startCall method and add the required A basic example of how to make changes to implement recording for a direct call/ a default call: + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + ```js @@ -137,3 +165,35 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: + +--- + + + + - **Inform users about recording** — Always notify participants when recording starts. This is often a legal requirement in many jurisdictions. + - **Use auto-start for compliance** — If all calls must be recorded for compliance, use `startRecordingOnCallStart(true)` to ensure no calls are missed. + - **Handle recording events** — Implement `onRecordingStarted` and `onRecordingStopped` listeners to update UI and inform users of recording status. + - **Check recording availability** — Recording is a premium feature. Verify it's enabled for your CometChat plan before implementing. + - **Plan for storage** — Recordings consume storage. Implement a retention policy and regularly download/archive recordings from the Dashboard. + + + - **Recording button not visible** — Ensure `showRecordingButton(true)` is set in CallSettings. The button is hidden by default. + - **Recording not starting** — Verify recording is enabled for your CometChat app in the Dashboard. Check that the call session is active before calling `startRecording()`. + - **Recording not appearing in Dashboard** — Recordings may take several minutes to process after a call ends. Check back later or filter by date range. + - **onRecordingStarted not firing** — Ensure the recording listener is registered before starting the session. Check that you're using the correct listener format. + - **Recording quality issues** — Recording quality depends on the source video/audio quality. Ensure participants have stable connections and good lighting for video. + + + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Retrieve and display call history for users and groups + + diff --git a/sdk/javascript/resources-overview.mdx b/sdk/javascript/resources-overview.mdx index ea0d211b..fce2b674 100644 --- a/sdk/javascript/resources-overview.mdx +++ b/sdk/javascript/resources-overview.mdx @@ -1,12 +1,33 @@ --- title: "Resources" sidebarTitle: "Overview" +description: "Access CometChat JavaScript SDK resources including real-time listeners reference, migration guides, and rate limits." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) — Complete listener reference +- [Upgrading from v3](/sdk/javascript/upgrading-from-v3) — Migration guide +- [Rate Limits](/sdk/javascript/rate-limits) — API rate limit details + We have a number of resources that will help you while integrating CometChat in your app. You can begin with the [all real-time listeners](/sdk/javascript/all-real-time-listeners) guide. If you're upgrading from v2, we recommend reading our [Upgrading from v3](/sdk/javascript/upgrading-from-v3) guide. + +--- + +## Next Steps + + + + Complete reference for all CometChat event listeners + + + Step-by-step migration guide from SDK v3 to v4 + + \ No newline at end of file diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index a58ef59d..c31330ef 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -1,11 +1,35 @@ --- title: "Retrieve Conversations" +description: "Fetch, filter, tag, and search conversations using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, agentic conversation filters, and message-to-conversation conversion." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch conversations list +const request = new CometChat.ConversationsRequestBuilder() + .setLimit(30).build(); +const conversations = await request.fetchNext(); + +// Get a specific conversation +const conversation = await CometChat.getConversation("UID", "user"); + +// Tag a conversation +await CometChat.tagConversation("UID", "user", ["archived"]); + +// Convert message to conversation +const conversation = await CometChat.CometChatHelper.getConversationFromMessage(message); +``` + Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Retrieve List of Conversations *In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* @@ -622,3 +646,16 @@ CometChat.CometChatHelper.getConversationFromMessage(message).then( While converting the `Message` object to the `Conversation` object, the `unreadMessageCount` & `tags` will not be available in the `Conversation` object. The unread message count needs to be managed in your client-side code. + +--- + +## Next Steps + + + + Remove conversations from the logged-in user's list + + + Show real-time typing status in conversations + + diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 3e21b909..ea304c69 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -1,9 +1,31 @@ --- title: "Retrieve Group Members" +description: "Fetch and filter group members by scope, status, and search keyword using the CometChat JavaScript SDK with pagination support." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch group members +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).build(); +const members = await request.fetchNext(); + +// Filter by scope +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setScopes(["admin", "moderator"]).build(); + +// Search members +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30).setSearchKeyword("john").build(); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve the List of Group Members In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. To use this class i.e to create an object of the GroupMembersRequest class, you need to use the `GroupMembersRequestBuilder` class. The `GroupMembersRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. @@ -187,3 +209,32 @@ groupMembersRequest.fetchNext().then( + + +- **Paginate results** — Always use `fetchNext()` in a loop or on-scroll. Set a reasonable limit (10–30) per request to avoid large payloads. +- **Reuse the request object** — Create the `GroupMembersRequest` once and call `fetchNext()` repeatedly. Creating a new builder each time resets pagination. +- **Filter by scope for admin panels** — Use `setScopes(["admin", "moderator"])` when building admin views to show only privileged members. +- **Use status filter for presence** — Filter by `CometChat.USER_STATUS.ONLINE` to show active members in real-time collaboration features. +- **Combine filters** — You can chain `setSearchKeyword()`, `setScopes()`, and `setStatus()` on the same builder for precise results. + + + +- **Empty member list returned** — Verify the GUID is correct and the logged-in user is a member of the group. Non-members cannot fetch member lists. +- **`fetchNext()` returns the same results** — You're likely creating a new `GroupMembersRequest` each time. Reuse the same instance for pagination. +- **Search not finding members** — `setSearchKeyword()` matches against member names. Ensure the keyword is correct and partially matches. +- **Scope filter returns no results** — Double-check the scope strings. Valid values are `"admin"`, `"moderator"`, and `"participant"`. +- **Status filter not working** — Use `CometChat.USER_STATUS.ONLINE` or `CometChat.USER_STATUS.OFFLINE` constants, not raw strings. + + +--- + +## Next Steps + + + + Add users to a group programmatically + + + Remove or ban members from a group + + diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 92a074c0..a3c2c03e 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -1,9 +1,33 @@ --- title: "Retrieve Groups" +description: "Fetch, filter, and search groups using the CometChat JavaScript SDK. Includes pagination, tag-based filtering, joined-only groups, and online member counts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch groups list +const request = new CometChat.GroupsRequestBuilder() + .setLimit(30).build(); +const groups = await request.fetchNext(); + +// Get specific group details +const group = await CometChat.getGroup("GUID"); + +// Fetch only joined groups +const request = new CometChat.GroupsRequestBuilder() + .setLimit(30).joinedOnly(true).build(); + +// Get online member count +const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve List of Groups *In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* @@ -213,7 +237,7 @@ To get the information of a group, you can use the `getGroup()` method. ```javascript -var GUID = "GUID"; +const GUID = "GUID"; CometChat.getGroup(GUID).then( group => { console.log("Group details fetched successfully:", group); @@ -227,7 +251,7 @@ group => { ```typescript -var GUID: string = "GUID"; +const GUID: string = "GUID"; CometChat.getGroup(GUID).then( (group: CometChat.Group) => { console.log("Group details fetched successfully:", group); @@ -283,3 +307,32 @@ CometChat.getOnlineGroupMemberCount(guids).then( This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. + + +- **Use pagination** — Always call `fetchNext()` in a loop or on-scroll rather than fetching all groups at once. Set a reasonable limit (10–30) per page. +- **Cache group details** — If you call `getGroup()` frequently for the same GUID, cache the result locally to reduce API calls. +- **Use `joinedOnly(true)` for navigation** — When building a sidebar or group list, filter to joined groups so users only see groups they belong to. +- **Combine filters wisely** — You can chain `setSearchKeyword()`, `setTags()`, and `joinedOnly()` on the same builder for precise results. +- **Use `withTags(true)` only when needed** — Fetching tags adds payload size. Only enable it when your UI displays or filters by tags. + + + +- **Empty group list returned** — Ensure the logged-in user has the correct permissions. Private groups only appear if the user is a member. +- **`fetchNext()` returns the same results** — You're likely creating a new `GroupsRequest` object each time. Reuse the same instance across pagination calls. +- **`getGroup()` fails with "Group not found"** — Verify the GUID is correct and the group hasn't been deleted. Password/private groups require membership. +- **Online member count returns 0** — The user must be a member of the group. Also confirm the GUIDs array is not empty. +- **Search not returning expected results** — `setSearchKeyword()` matches against the group name. Ensure the keyword is spelled correctly and is at least partially matching. + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Fetch and filter members of a specific group + + diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index 943df640..cc07b410 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -1,9 +1,32 @@ --- title: "Retrieve Users" +description: "Fetch, filter, search, and sort users using the CometChat JavaScript SDK. Includes pagination, role-based filtering, tag support, and online user counts." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch users list +const request = new CometChat.UsersRequestBuilder() + .setLimit(30).build(); +const users = await request.fetchNext(); + +// Get specific user details +const user = await CometChat.getUser("UID"); +// Get logged-in user +const me = await CometChat.getLoggedinUser(); + +// Get online user count +const count = await CometChat.getOnlineUserCount(); +``` + + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Retrieve Logged In User Details You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. @@ -420,10 +443,10 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the UsersRequest class, you need to call the fetchNext() method. Calling this method will return a list of User objects containing n number of users where n is the limit set in the builder class. - + ```javascript -var limit = 30; -var usersRequest = new CometChat.UsersRequestBuilder() +const limit = 30; +const usersRequest = new CometChat.UsersRequestBuilder() .setLimit(limit) .build(); @@ -535,3 +558,35 @@ CometChat.getOnlineUserCount().then( This method returns the total online user count for your app. + +--- + + + + - **Paginate results** — Use `setLimit()` with reasonable values (30-50) and call `fetchNext()` for subsequent pages. Don't fetch all users at once. + - **Reuse the request object** — Call `fetchNext()` on the same `UsersRequest` instance for pagination. Creating a new object resets the cursor. + - **Filter strategically** — Combine `setStatus()`, `setRoles()`, and `setTags()` to narrow results efficiently rather than filtering client-side. + - **Cache user details** — Store frequently accessed user objects locally to reduce API calls, especially for `getUser()`. + - **Use `hideBlockedUsers(true)`** — Enable this in user lists to respect block relationships and provide a cleaner experience. + + + - **Empty user list returned** — Check that users exist in your CometChat app. Verify filters aren't too restrictive by removing them one at a time. + - **Pagination not working** — Ensure you're reusing the same `UsersRequest` object for `fetchNext()` calls. Creating a new builder resets pagination. + - **`getUser()` returns error** — Verify the UID exists and is spelled correctly. UIDs are case-sensitive. + - **Online count seems wrong** — `getOnlineUserCount()` returns the total across your app, not just the current user's contacts. Users must have an active connection. + - **Search not finding users** — By default, search checks both UID and name. Use `searchIn()` to limit search scope if needed. + + + +--- + +## Next Steps + + + + Track and subscribe to user online/offline status + + + Block and unblock users from your application + + diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index ae9f8e12..711d2a8d 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1,11 +1,37 @@ --- title: "Send A Message" +description: "Send text, media, and custom messages to users and groups using the CometChat JavaScript SDK. Includes metadata, tags, quoted messages, and multiple attachments." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send text message to user +const msg = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(msg); + +// Send text message to group +const msg = new CometChat.TextMessage("GUID", "Hello!", CometChat.RECEIVER_TYPE.GROUP); +await CometChat.sendMessage(msg); + +// Send media message +const msg = new CometChat.MediaMessage("UID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMediaMessage(msg); + +// Send custom message +const msg = new CometChat.CustomMessage("UID", CometChat.RECEIVER_TYPE.USER, "customType", { key: "value" }); +await CometChat.sendCustomMessage(msg); +``` + Using CometChat, you can send three types of messages: + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + 1. [Text Message](/sdk/javascript/send-message#text-message) is the most common and standard message type. 2. [Media Message](/sdk/javascript/send-message#media-message) for sending photos, videos and files. 3. [Custom Message](/sdk/javascript/send-message#custom-message), for sending completely custom data using JSON structures. @@ -170,6 +196,27 @@ CometChat.sendMessage(textMessage).then( + +```javascript +try { + const receiverID = "UID"; + const messageText = "Hello world!"; + const receiverType = CometChat.RECEIVER_TYPE.USER; + const textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + const message = await CometChat.sendMessage(textMessage); + console.log("Message sent successfully:", message); +} catch (error) { + console.log("Message sending failed with error:", error); +} +``` + + + ### Set Quoted Message Id @@ -400,11 +447,11 @@ Getting file Object: @@ -547,11 +594,11 @@ Getting file Object: @@ -831,11 +878,11 @@ Getting files: @@ -1725,3 +1772,33 @@ CometChat.sendCustomMessage(customMessage).then( It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/javascript/interactive-messages) + + +- **Use appropriate message types**: Choose text, media, or custom messages based on your content +- **Add metadata for context**: Use `setMetadata()` to attach location, device info, or other contextual data +- **Tag important messages**: Use `setTags()` to mark messages for easy filtering (e.g., "starred", "important") +- **Handle errors gracefully**: Always implement error callbacks to handle network issues or invalid parameters +- **Use async/await for cleaner code**: Modern JavaScript syntax makes message sending code more readable +- **Validate file types**: Before sending media messages, verify the file type matches the message type (IMAGE, VIDEO, AUDIO, FILE) + + + +- **Message not sent** — Ensure `CometChat.login()` succeeded before sending. The user must be logged in. +- **Media upload fails** — Check file size limits in your CometChat plan. Verify the file type matches the message type. +- **Custom message not received** — Ensure the receiver has an `onCustomMessageReceived` handler registered. +- **Metadata not appearing** — Use `setMetadata()` before calling the send method, not after. +- **Quoted message fails** — Verify the quoted message ID exists and belongs to the same conversation. + + +--- + +## Next Steps + + + + Listen for incoming messages in real-time and fetch missed messages + + + Edit previously sent text and custom messages + + diff --git a/sdk/javascript/session-timeout.mdx b/sdk/javascript/session-timeout.mdx index 23470881..f07d8414 100644 --- a/sdk/javascript/session-timeout.mdx +++ b/sdk/javascript/session-timeout.mdx @@ -1,8 +1,18 @@ --- title: "Session Timeout Flow" +description: "Handle idle session timeouts in CometChat calls, including automatic termination, user prompts, and the onSessionTimeout event." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- Default idle timeout: 180 seconds (3 minutes) alone in a session +- Warning dialog appears at 120 seconds with stay/leave options +- Auto-terminates after 60 more seconds if no action taken +- Listen for `onSessionTimeout` event to handle auto-termination +- Customize timeout with `setIdleTimeoutPeriod(seconds)` in CallSettings (v4.1.0+) + Available since v4.1.0 @@ -32,3 +42,33 @@ This feature helps manage inactive call sessions and prevents unnecessary resour The `onSessionTimeout` event is triggered when the call automatically terminates due to session timeout, as illustrated in the diagram above. + +--- + + + + - **Customize timeout for your use case** — Use `setIdleTimeoutPeriod()` to adjust the timeout based on your application's needs. Longer timeouts for waiting rooms, shorter for quick calls. + - **Handle the warning dialog** — The 60-second warning gives users time to decide. Ensure your UI doesn't block or hide this dialog. + - **Implement onSessionTimeout** — Always handle the `onSessionTimeout` event to properly clean up resources and update your UI when auto-termination occurs. + - **Consider disabling for specific scenarios** — For use cases like webinars or waiting rooms where users may be alone for extended periods, consider increasing or disabling the timeout. + + + - **Timeout happening too quickly** — The default is 180 seconds (3 minutes). Use `setIdleTimeoutPeriod()` to increase if needed. + - **Warning dialog not appearing** — The dialog appears at 120 seconds of being alone. If using a custom layout (`enableDefaultLayout(false)`), you need to implement your own warning UI. + - **onSessionTimeout not firing** — Ensure you've registered the listener before starting the session. This event only fires on auto-termination, not manual end. + - **Timeout not resetting** — The timer resets when another participant joins. If it's not resetting, verify the other participant successfully joined the session. + + + +--- + +## Next Steps + + + + Implement ringing call flows with accept/reject functionality + + + Implement calling without the Chat SDK + + diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index e9bdce87..c6a0a594 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -1,10 +1,32 @@ --- title: "Setup" sidebarTitle: "Overview" +description: "Install, configure, and initialize the CometChat JavaScript SDK in your application using npm or CDN." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** +```bash +# Install +npm install @cometchat/chat-sdk-javascript +``` + +```javascript +import { CometChat } from "@cometchat/chat-sdk-javascript"; + +// Initialize (run once at app start) +const appSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .autoEstablishSocketConnection(true) + .build(); +await CometChat.init("APP_ID", appSettings); +``` +**Required:** App ID, Region from [CometChat Dashboard](https://app.cometchat.com) → API & Auth Keys + Migrating app version from v3 to v4 ? @@ -23,11 +45,11 @@ Follow steps mentioned in **Add the CometChat dependency** section below to upgr ## Add the CometChat Dependency -### NPM +### Package Manager - -```js + +```bash npm install @cometchat/chat-sdk-javascript ``` @@ -124,11 +146,97 @@ CometChat.init(appID, appSetting).then( + +```javascript +let appID = "APP_ID"; +let region = "APP_REGION"; +let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + +try { + await CometChat.init(appID, appSetting); + console.log("Initialization completed successfully"); +} catch (error) { + console.log("Initialization failed with error:", error); +} +``` + + + Make sure you replace the `APP_ID` with your CometChat **App ID** and `APP_REGION` with your **App Region** in the above code. + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + + + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + | Parameter | Description | | ---------- | ----------------------------------- | | appID | CometChat App ID | | appSetting | An object of the AppSettings class. | + +### AppSettings Configuration Options + +| Method | Description | Default | +| --- | --- | --- | +| `setRegion(region)` | The region where your app was created (`us`, `eu`, `in`, `in-private`) | Required | +| `subscribePresenceForAllUsers()` | Subscribe to presence events for all users | — | +| `subscribePresenceForRoles(roles)` | Subscribe to presence events for specific roles | — | +| `subscribePresenceForFriends()` | Subscribe to presence events for friends only | — | +| `autoEstablishSocketConnection(bool)` | Let the SDK manage WebSocket connections internally | `true` | +| `overrideAdminHost(adminHost)` | Use a custom admin URL (dedicated deployment) | — | +| `overrideClientHost(clientHost)` | Use a custom client URL (dedicated deployment) | — | +| `setStorageMode(storageMode)` | Configure local storage mode (`CometChat.StorageMode.SESSION` for session storage) | — | + + +**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the [Overview page](/sdk/javascript/overview#server-side-rendering-ssr-compatibility) for framework-specific examples. + + +## Best Practices + + + + Call `CometChat.init()` as early as possible in your application lifecycle — typically in your entry file (`index.js`, `main.js`, or `App.js`). It only needs to be called once per app session. + + + Use `CometChat.getLoggedinUser()` to check if a user session already exists before calling `login()`. This avoids unnecessary login calls and improves app startup time. + + + Store your App ID, Region, and Auth Key in environment variables rather than hardcoding them. This makes it easier to switch between development and production environments. + + + +## Troubleshooting + + + + Verify your App ID is correct and matches the one in your [CometChat Dashboard](https://app.cometchat.com). Ensure you're using the right region (`us`, `eu`, `in`, or `in-private`). + + + This means `init()` was not called or hasn't completed before other SDK methods were invoked. Ensure `init()` resolves successfully before calling `login()`, `sendMessage()`, or registering listeners. + + + If you're behind a corporate firewall or proxy, WebSocket connections may be blocked. Check your network configuration. You can also manage WebSocket connections manually — see [Managing WebSocket Connections](/sdk/javascript/managing-web-sockets-connections-manually). + + + +--- + +## Next Steps + + + + Log in users with Auth Key or Auth Token + + + Send your first text, media, or custom message + + diff --git a/sdk/javascript/standalone-calling.mdx b/sdk/javascript/standalone-calling.mdx index 09df82d0..d576f9f0 100644 --- a/sdk/javascript/standalone-calling.mdx +++ b/sdk/javascript/standalone-calling.mdx @@ -1,7 +1,28 @@ --- title: "Standalone Calling" +description: "Implement video and audio calling using only the CometChat Calls SDK without the Chat SDK. Covers authentication, token generation, session management, and call controls." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Generate call token (requires user auth token from REST API) +const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); + +// Start call session +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .setCallListener(callListener) + .build(); +CometChatCalls.startSession(callToken.token, callSettings, htmlElement); + +// End session +CometChatCalls.endSession(); +``` + ## Overview This section demonstrates how to implement calling functionality using only the CometChat Calls SDK, without requiring the Chat SDK. This is ideal for applications that need video/audio calling capabilities without the full chat infrastructure. @@ -228,6 +249,10 @@ Configure the call experience using the following `CallSettingsBuilder` methods: The `OngoingCallListener` provides real-time callbacks for call session events, including participant changes, call state updates, and error conditions. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You can register listeners in two ways: 1. **Via CallSettingsBuilder:** Use `.setCallListener(listener)` when building call settings @@ -647,3 +672,35 @@ CometChatCalls.endSession(); ``` + +--- + + + + - **Secure auth token handling** — Never expose auth tokens in client-side code. Generate them server-side and pass securely to the client. + - **Use consistent session IDs** — For participants to join the same call, they must use the same session ID. Generate a unique ID and share it through your backend. + - **Implement proper cleanup** — Always call `endSession()` when leaving a call to release camera, microphone, and network resources. + - **Handle all listener events** — Implement handlers for all `OngoingCallListener` events to provide a complete user experience. + - **Test without Chat SDK** — Standalone calling doesn't require Chat SDK initialization. Verify your implementation works independently. + + + - **Invalid auth token** — Auth tokens obtained from REST API may expire. Implement token refresh logic or generate new tokens as needed. + - **Participants can't join same call** — Ensure all participants are using the exact same session ID. Session IDs are case-sensitive. + - **No user context** — Unlike the Chat SDK flow, standalone calling doesn't have automatic user context. User information comes from the auth token. + - **Call not connecting** — Verify the Calls SDK is initialized with correct App ID and Region. Check that both participants have valid call tokens. + - **Missing user info in callbacks** — User details in callbacks come from the auth token. Ensure the token was generated for a user with complete profile information. + + + +--- + +## Next Steps + + + + Implement ringing call flows using the Chat SDK + + + Add call recording to your voice and video calls + + diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index e2d29a55..08235778 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -1,11 +1,35 @@ --- title: "Threaded Messages" +description: "Send, receive, and fetch threaded messages using the CometChat JavaScript SDK. Includes real-time listeners, thread message history, and filtering thread replies." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send message in a thread +const msg = new CometChat.TextMessage("UID", "Reply", CometChat.RECEIVER_TYPE.USER); +msg.setParentMessageId(100); +await CometChat.sendMessage(msg); + +// Fetch thread messages +const request = new CometChat.MessagesRequestBuilder() + .setParentMessageId(100).setLimit(30).build(); +const messages = await request.fetchPrevious(); + +// Exclude thread replies from main conversation +const request = new CometChat.MessagesRequestBuilder() + .setUID("UID").setLimit(30).hideReplies(true).build(); +``` + Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send Message in a Thread As mentioned in the [Send a Message](/sdk/javascript/send-message) section. You can either send a message to a User or a Group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to either of the below types: @@ -67,13 +91,17 @@ Similarly, using the `setParentMessageId()` method, Media and Custom Messages ca The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/javascript/receive-message). This can be achieved using the `MessageListener` class provided by the SDK. + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + To add a MessageListener, you can use the `addMessageListener()` method of the SDK. The only thing that needs to be checked is if the received message belongs to the active thread. This can be done using the `parentMessageId` field of the message object. ```javascript -var listenerID = "UNIQUE_LISTENER_ID"; -var activeThreadId = 100; +const listenerID = "UNIQUE_LISTENER_ID"; +const activeThreadId = 100; CometChat.addMessageListener( listenerID, @@ -101,8 +129,8 @@ new CometChat.MessageListener({ ```typescript -var listenerID: string = "UNIQUE_LISTENER_ID", - activeThreadId: number = 100; +const listenerID: string = "UNIQUE_LISTENER_ID"; +const activeThreadId: number = 100; CometChat.addMessageListener( listenerID, @@ -271,3 +299,31 @@ messagesRequest.fetchPrevious().then( The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. + + +- **Track active thread ID**: Store the current thread's `parentMessageId` to filter incoming messages +- **Use `hideReplies(true)`**: Exclude thread replies from main conversation to avoid clutter +- **Paginate thread messages**: Use `setLimit()` and `fetchPrevious()` for large threads +- **Remove listeners on thread close**: Clean up message listeners when user exits a thread view +- **Show reply count**: Display the number of replies on parent messages to indicate thread activity + + + +- **Thread replies appearing in main chat** — Add `.hideReplies(true)` to your `MessagesRequestBuilder` to exclude thread replies from the main conversation. +- **Missing thread messages** — Verify `setParentMessageId()` uses the correct parent message ID. +- **Real-time messages not filtered** — Compare `getParentMessageId()` with the active thread ID to filter incoming messages. +- **Empty thread** — The parent message may have been deleted. Handle this case gracefully in your UI. + + +--- + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for incoming messages in real-time and fetch missed messages + + diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index 1de52a89..32db039a 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -1,11 +1,26 @@ --- title: "Transfer Group Ownership" +description: "Transfer ownership of a CometChat group to another member using the JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Transfer group ownership +await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); +``` + +**Note:** Only the current group owner can transfer ownership. The owner must transfer ownership before leaving the group. + *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + In order to transfer the ownership of any group, the first condition is that you must be the owner of the group. In case you are the owner of the group, you can use the `transferGroupOwnership()` method provided by the `CometChat` class. This will be helpful as the owner is not allowed to leave the group. In case, you as the owner would like to leave the group, you will have to use this method and transfer your ownership first to any other member of the group and only then you will be allowed to leave the group. @@ -42,3 +57,30 @@ CometChat.transferGroupOwnership(GUID, UID).then( + + +- **Transfer before leaving** — The owner cannot leave a group without first transferring ownership. Always call `transferGroupOwnership()` before `leaveGroup()`. +- **Choose a trusted member** — Transfer ownership to an active admin or moderator who can manage the group responsibly. +- **Confirm in UI** — Ownership transfer is irreversible. Add a confirmation dialog before calling the method. +- **Update local state** — After a successful transfer, update your local group data to reflect the new owner. + + + +- **"ERR_NOT_A_MEMBER" or permission error** — Only the current group owner can transfer ownership. Verify the logged-in user is the owner. +- **Transfer fails with "User not found"** — The target UID must be an existing member of the group. Verify the UID and their membership status. +- **Owner still can't leave after transfer** — Ensure the `transferGroupOwnership()` promise resolved successfully before calling `leaveGroup()`. +- **New owner doesn't have admin privileges** — After ownership transfer, the new owner automatically gets the owner role. If the UI doesn't reflect this, re-fetch the group details. + + +--- + +## Next Steps + + + + Leave a group after transferring ownership + + + Promote or demote group members + + diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index 9f44b226..d6bda9cb 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -1,11 +1,30 @@ --- title: "Transient Messages" +description: "Send and receive ephemeral real-time messages that are not stored on the server using the CometChat JavaScript SDK. Ideal for live reactions and temporary indicators." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Send transient message to user +const msg = new CometChat.TransientMessage("UID", CometChat.RECEIVER_TYPE.USER, { LIVE_REACTION: "heart" }); +CometChat.sendTransientMessage(msg); + +// Listen for transient messages +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTransientMessageReceived: (msg) => console.log("Transient:", msg) +})); +``` + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Send a Transient Message You can use the `sendTransientMessage()` method to send a transient message to a user or in a group. The receiver will receive this information in the `onTransientMessageReceived()` method of the `MessageListener` class. In order to send the transient message, you need to use the `TransientMessage` class. @@ -65,6 +84,10 @@ CometChat.sendTransientMessage(transientMessage); *In other words, as a recipient, how do I know when someone sends a transient message?* + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. @@ -110,3 +133,16 @@ The `TransientMessage` class consists of the below parameters: | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the transient message is sent to. | | **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | | **data** | A JSONObject to provide data. | + +--- + +## Next Steps + + + + Show real-time typing status in conversations + + + Send text, media, and custom messages + + diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 0174f572..c7296e70 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -1,9 +1,31 @@ --- title: "Typing Indicators" +description: "Send and receive real-time typing indicators for users and groups using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Start typing indicator +const typing = new CometChat.TypingIndicator("UID", CometChat.RECEIVER_TYPE.USER); +CometChat.startTyping(typing); + +// Stop typing indicator +CometChat.endTyping(typing); + +// Listen for typing events +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTypingStarted: (indicator) => console.log("Typing started:", indicator), + onTypingEnded: (indicator) => console.log("Typing ended:", indicator) +})); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Send a Typing Indicator *In other words, as a sender, how do I let the recipient(s) know that I'm typing?* @@ -121,6 +143,10 @@ You can use the `metadata` field of the `TypingIndicator` class to pass addition *In other words, as a recipient, how do I know when someone is typing?* + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + + You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. @@ -172,3 +198,31 @@ The `TypingIndicator` class consists of the below parameters: | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the typing indicator is sent to. | | **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | | **metadata** | A JSONObject to provider additional data. | + + +- **Debounce typing events**: Don't call `startTyping()` on every keystroke - debounce to ~300ms intervals +- **Auto-stop typing**: Call `endTyping()` after a period of inactivity (e.g., 3-5 seconds) +- **Stop on send**: Always call `endTyping()` when the user sends a message +- **Use unique listener IDs**: Prevent duplicate events by using component-specific listener IDs +- **Remove listeners on unmount**: Clean up listeners when leaving a conversation view + + + +- **Typing indicator not showing** — Verify `addMessageListener()` is called before typing starts. The listener must be registered first. +- **Indicator stuck on "typing"** — Ensure `endTyping()` is called on message send, input blur, or after a timeout (3-5 seconds of inactivity). +- **Multiple typing events firing** — Use unique listener IDs and remove listeners on component unmount to prevent duplicates. +- **Wrong user shown typing** — Verify the `receiverId` matches the current conversation's UID or GUID. + + +--- + +## Next Steps + + + + Track when messages are delivered and read + + + Send ephemeral real-time messages like live reactions + + diff --git a/sdk/javascript/update-group.mdx b/sdk/javascript/update-group.mdx index c8717d61..6e2b791e 100644 --- a/sdk/javascript/update-group.mdx +++ b/sdk/javascript/update-group.mdx @@ -1,9 +1,22 @@ --- title: "Update A Group" +description: "Update group details such as name, type, icon, and description using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Update group details +const group = new CometChat.Group("GUID", "New Name", CometChat.GROUP_TYPE.PUBLIC); +const updated = await CometChat.updateGroup(group); +``` + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + ## Update Group *In other words, as a group owner, how can I update the group details?* @@ -13,10 +26,10 @@ You can update the existing details of the group using the `updateGroup()` metho ```javascript -var GUID = "GUID"; -var groupName = "Hello Group"; -var groupType = CometChat.GROUP_TYPE.PUBLIC; -var group = new CometChat.Group(GUID, groupName, groupType); +const GUID = "GUID"; +const groupName = "Hello Group"; +const groupType = CometChat.GROUP_TYPE.PUBLIC; +const group = new CometChat.Group(GUID, groupName, groupType); CometChat.updateGroup(group).then( group => { @@ -31,11 +44,11 @@ group => { ```typescript -var GUID: string = "GUID"; -var groupName: string = "Hello Group!"; -var groupType: string = CometChat.GROUP_TYPE.PUBLIC; +const GUID: string = "GUID"; +const groupName: string = "Hello Group!"; +const groupType: string = CometChat.GROUP_TYPE.PUBLIC; -var group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); +const group: CometChat.Group = new CometChat.Group(GUID, groupName, groupType); CometChat.updateGroup(group).then( (group: CometChat.Group) => { @@ -59,3 +72,33 @@ This method takes an instance of the `Group` class as a parameter which should c After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. For more information on the `Group` class, please check [here](/sdk/javascript/create-group#create-a-group). + +--- + + + + - **Only update changed fields** — Set only the fields you want to change on the Group object. Unchanged fields retain their current values. + - **Validate before updating** — Check that the user has admin or moderator scope before showing update options in your UI. + - **Update metadata carefully** — When updating metadata, merge with existing data rather than replacing it entirely to avoid losing other fields. + - **Refresh after update** — After a successful update, refresh the group details in your UI to reflect the changes. + + + - **"Not authorized" error** — Only admins and moderators can update group details. Check the user's scope. + - **Group type not changing** — Group type cannot be changed after creation. This is by design. + - **Update not reflected** — Ensure the update promise resolved successfully. Other members receive the update via `GroupListener`. + - **Metadata overwritten** — When updating metadata, the entire metadata object is replaced. Merge with existing metadata before updating. + + + +--- + +## Next Steps + + + + Permanently delete a group + + + Fetch and filter groups with pagination + + diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 00cf6868..c5d1aff1 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -1,9 +1,18 @@ --- title: "Upgrading From V3" +description: "Migrate your CometChat JavaScript SDK integration from v3 to v4 with updated dependencies and import statements." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** - +Key changes from v3 to v4: +- Chat SDK: `npm i @cometchat/chat-sdk-javascript` +- Calls SDK: `npm i @cometchat/calls-sdk-javascript` +- Import: `import { CometChat } from '@cometchat/chat-sdk-javascript'` +- Import Calls: `import { CometChatCalls } from '@cometchat/calls-sdk-javascript'` + ## Upgrading From v3 Upgrading from v3.x to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4: @@ -63,3 +72,30 @@ import {CometChatCalls} from '@cometchat/calls-sdk-javascript'; + + +- **Follow the setup guide first** — Complete the v4 [setup instructions](/sdk/javascript/setup-sdk) before changing imports, so you have the latest SDK version installed. +- **Update all imports at once** — Use find-and-replace across your project to change all `@cometchat-pro/chat` imports to `@cometchat/chat-sdk-javascript` in one pass. +- **Test incrementally** — After updating dependencies and imports, test each feature area (messaging, calling, groups) individually to catch any breaking changes. +- **Remove old packages** — After migration, uninstall the v3 packages (`npm uninstall @cometchat-pro/chat`) to avoid conflicts. + + + +- **"Module not found" errors after upgrade** — You likely have old import paths. Search your project for `@cometchat-pro/chat` and replace with `@cometchat/chat-sdk-javascript`. +- **Calls SDK not working** — The calls SDK package name also changed. Use `@cometchat/calls-sdk-javascript` instead of the v3 package. +- **TypeScript type errors** — Some type definitions may have changed between v3 and v4. Check the [changelog](https://github.com/cometchat/chat-sdk-javascript/releases) for breaking type changes. +- **Both v3 and v4 installed** — Having both versions can cause conflicts. Remove the v3 package completely before installing v4. + + +--- + +## Next Steps + + + + Install and configure the CometChat JavaScript SDK + + + Learn the core concepts behind CometChat v4 + + diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index 76ac2b58..44059206 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -1,11 +1,35 @@ --- title: "User Management" +description: "Create, update, and manage CometChat users programmatically using the JavaScript SDK. Includes user creation, profile updates, and the User class reference." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Create a user +const user = new CometChat.User("user1"); +user.setName("Kevin"); +await CometChat.createUser(user, "AUTH_KEY"); + +// Update a user +user.setName("Kevin Fernandez"); +await CometChat.updateUser(user, "AUTH_KEY"); + +// Update logged-in user (no auth key needed) +await CometChat.updateCurrentUserDetails(user); +``` + +**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + Summing up- **When a user registers in your app** @@ -22,51 +46,51 @@ Summing up- Ideally, user creation should take place at your backend. You can refer our Rest API to learn more about [creating a user](https://api-explorer.cometchat.com/reference/creates-user) and use the appropriate code sample based on your backend language. + +**Security:** Never expose your `Auth Key` in client-side production code. User creation and updates using `Auth Key` should ideally happen on your backend server. Use client-side creation only for prototyping or development. + + However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. -```js +```javascript let authKey = "AUTH_KEY"; -var uid = "user1"; -var name = "Kevin"; +let uid = "user1"; +let name = "Kevin"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( user => { - console.log("user created", user); + console.log("user created", user); }, error => { - console.log("error", error); + console.log("error", error); } ) ``` - - ```typescript let authKey: string = "AUTH_KEY"; -var uid: string = "user1"; -var name: string = "Kevin"; +let uid: string = "user1"; +let name: string = "Kevin"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.createUser(user, authKey).then( (user: CometChat.User) => { - console.log("user created", user); + console.log("user created", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } ); ``` - - @@ -81,47 +105,43 @@ Updating a user similar to creating a user should ideally be achieved at your ba -```js +```javascript let authKey = "AUTH_KEY"; let uid = "user1"; let name = "Kevin Fernandez"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( user => { - console.log("user updated", user); + console.log("user updated", user); }, error => { - console.log("error", error); + console.log("error", error); } -) +) ``` - - ```typescript let authKey: string = "AUTH_KEY"; -var uid: string = "user1"; -var name: string = "Kevin Fernandez"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateUser(user, authKey).then( (user: CometChat.User) => { - console.log("user updated", user); + console.log("user updated", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } -) +) ``` - - Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. @@ -132,45 +152,41 @@ Updating a logged-in user is similar to updating a user. The only difference bei -```js +```javascript let uid = "user1"; let name = "Kevin Fernandez"; -var user = new CometChat.User(uid); +let user = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( user => { - console.log("user updated", user); + console.log("user updated", user); }, error => { - console.log("error", error); + console.log("error", error); } ) ``` - - ```typescript -var uid: string = "user1"; -var name: string = "Kevin Fernandez"; +let uid: string = "user1"; +let name: string = "Kevin Fernandez"; -var user: CometChat.User = new CometChat.User(uid); +let user: CometChat.User = new CometChat.User(uid); user.setName(name); CometChat.updateCurrentUserDetails(user).then( (user: CometChat.User) => { - console.log("user updated", user); + console.log("user updated", user); }, (error: CometChat.CometChatException) => { - console.log("error", error); + console.log("error", error); } ); ``` - - By using the `updateCurrentUserDetails()` method one can only update the logged-in user irrespective of the UID passed. Also, it is not possible to update the role of a logged-in user. @@ -195,3 +211,35 @@ Deleting a user can only be achieved via the Restful APIs. For more information | hasBlockedMe | No | A boolean that determines if the user has blocked the logged in user | | blockedByMe | No | A boolean that determines if the logged in user has blocked the user | | tags | Yes | A list of tags to identify specific users | + + + +- **Backend user creation** — Always create and update users from your backend server using the REST API to keep your `Auth Key` secure. +- **UID format** — Use alphanumeric characters, underscores, and hyphens only. Avoid spaces and special characters. +- **Metadata usage** — Store additional user info (e.g., department, preferences) in the `metadata` JSON field rather than creating custom fields. +- **Sync on registration** — Create the CometChat user immediately when a user registers in your app to avoid login failures. + + +- **`createUser()` fails with "Auth Key not found"** — Invalid or missing Auth Key. Verify the Auth Key from your [CometChat Dashboard](https://app.cometchat.com). +- **`createUser()` fails with "UID already exists"** — A user with that UID was already created. Use `updateUser()` instead, or choose a different UID. +- **`updateCurrentUserDetails()` doesn't update role** — Role cannot be changed for the logged-in user. Use `updateUser()` with Auth Key from your backend to change roles. +- **User not appearing in user list** — The user was created but not yet indexed. Wait a moment and retry. Ensure `createUser()` resolved successfully. + + + +## Next Steps + + + + Fetch and filter user lists with pagination. + + + Monitor real-time online/offline status. + + + Block and unblock users. + + + Log users into CometChat. + + diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 503bc0d6..31d1665d 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -1,12 +1,36 @@ --- title: "User Presence" sidebarTitle: "Overview" +description: "Track real-time user online/offline status and configure presence subscriptions using the CometChat JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Subscribe to presence during init +const appSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() // or .subscribePresenceForRoles([]) / .subscribePresenceForFriends() + .setRegion("REGION").build(); + +// Listen for presence changes +CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener({ + onUserOnline: (user) => console.log("Online:", user), + onUserOffline: (user) => console.log("Offline:", user) +})); + +// Remove listener +CometChat.removeUserListener("LISTENER_ID"); +``` + User Presence helps us understand if a user is available to chat or not. + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + + ## Real-time Presence *In other words, as a logged-in user, how do I know if a user is online or offline?* @@ -23,28 +47,30 @@ For presence subscription, the AppSettingsBuilder provides 3 methods : If none of the above methods are used, no presence will be sent to the logged-in user. + +You must configure presence subscription in `AppSettings` during `CometChat.init()` before any presence events will be delivered. See [Setup SDK](/sdk/javascript/setup-sdk) for details. + + You need to register the `UserListener` using the `addUserListener()` method where ever you wish to receive these events in. - -``` + +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( -listenerID, -new CometChat.UserListener({ - onUserOnline: onlineUser => { - console.log("On User Online:", { onlineUser }); - }, - onUserOffline: offlineUser => { - console.log("On User Offline:", { offlineUser }); - } -}) -); + listenerID, + new CometChat.UserListener({ + onUserOnline: onlineUser => { + console.log("On User Online:", { onlineUser }); + }, + onUserOffline: offlineUser => { + console.log("On User Offline:", { offlineUser }); + } + }) +); ``` - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; @@ -52,18 +78,16 @@ let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.addUserListener( listenerID, new CometChat.UserListener({ - onUserOnline: (onlineUser: CometChat.User) => { - console.log("On User Online:", { onlineUser }); - }, - onUserOffline: (offlineUser: CometChat.User) => { - console.log("On User Offline:", { offlineUser }); - } + onUserOnline: (onlineUser: CometChat.User) => { + console.log("On User Online:", { onlineUser }); + }, + onUserOffline: (offlineUser: CometChat.User) => { + console.log("On User Offline:", { offlineUser }); + } }) ); ``` - - | Parameter | Description | @@ -72,29 +96,33 @@ CometChat.addUserListener( You will receive an object of the `User` class in the listener methods. -We recommend you remove the listener once the activity or view is not in use. - -We suggest adding this method when not in use. + +**Listener Cleanup:** Always remove the listener when the component or view is unmounted/destroyed to prevent memory leaks and duplicate callbacks. Use `CometChat.removeUserListener(listenerID)` in your cleanup logic. + - -``` + +```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` - - ```typescript let listenerID: string = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); ``` - - + +Always remove your `UserListener` when the component or view unmounts to prevent memory leaks and duplicate event handling. + +```javascript +CometChat.removeUserListener("LISTENER_ID"); +``` + + ## User List Presence *In other words, as a logged-in user, when I retrieve the user list, how do I know if a user is online/offline?* @@ -107,3 +135,35 @@ When you fetch the list of users, in the [User](/sdk/javascript/user-management# * offline - This indicates that the user is currently offline and is not available to chat. 2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. + + + +- **Choose the right subscription** — Use `subscribePresenceForFriends()` or `subscribePresenceForRoles()` instead of `subscribePresenceForAllUsers()` in apps with many users to reduce unnecessary events. +- **Use unique listener IDs** — Use unique, descriptive listener IDs (e.g., `"chat-screen-presence"`) to avoid accidentally overwriting other listeners. +- **Cleanup on unmount** — Always call `removeUserListener()` when the component/view is destroyed. +- **Combine with user list** — Use the `status` field from `UsersRequest` results for initial state, then update via `UserListener` for real-time changes. + + +- **No presence events received** — Presence subscription not configured in `AppSettings`. Add `subscribePresenceForAllUsers()`, `subscribePresenceForRoles()`, or `subscribePresenceForFriends()` to your `AppSettingsBuilder`. +- **Presence events stop after navigation** — The listener was removed or the component unmounted. Re-register the listener when the component mounts again. +- **Duplicate presence events** — Multiple listeners registered with the same or different IDs. Ensure you remove old listeners before adding new ones. +- **`lastActiveAt` is `0` or `null`** — The user has never been online or data is not yet available. Handle this in your UI with a fallback like "Never active". + + + +## Next Steps + + + + Fetch user lists with filtering and pagination. + + + Create and update users programmatically. + + + Monitor SDK connection to CometChat servers. + + + Overview of all available real-time listeners. + + diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index 2193624f..98246d43 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -1,10 +1,36 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Overview of CometChat user functionality including user management, retrieval, and presence tracking in the JavaScript SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +- [User Management](/sdk/javascript/user-management) — Create and update users +- [Retrieve Users](/sdk/javascript/retrieve-users) — Fetch and filter user lists +- [User Presence](/sdk/javascript/user-presence) — Track online/offline status +- [Block Users](/sdk/javascript/block-users) — Block and unblock users + The primary aim for our Users functionality is to allow you to quickly retrieve and add users to CometChat. You can begin with [user management](/sdk/javascript/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/javascript/retrieve-users) and display them in your app. + +## Next Steps + + + + Create, update, and delete users in CometChat. + + + Fetch user lists with filtering, sorting, and pagination. + + + Monitor real-time online/offline status of users. + + + Block and unblock users to control communication. + + diff --git a/sdk/javascript/video-view-customisation.mdx b/sdk/javascript/video-view-customisation.mdx index 2fd63257..6fc990af 100644 --- a/sdk/javascript/video-view-customisation.mdx +++ b/sdk/javascript/video-view-customisation.mdx @@ -1,9 +1,25 @@ --- title: "Video View Customisation" +description: "Customize the main video container in CometChat calls including aspect ratio, full screen button, name labels, and network labels." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Customize main video container +const videoSettings = new CometChat.MainVideoContainerSetting(); +videoSettings.setMainVideoAspectRatio(CometChat.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNameLabelParams(CometChat.CallSettings.POSITION_BOTTOM_LEFT, true, "rgba(27,27,27,0.4)"); +// Apply to call settings +const callSettings = new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + .build(); +``` + This section will guide you to customise the main video container. ## Implementation @@ -39,3 +55,35 @@ videoSettings.setNetworkLabelParams(CometChat.CallSettings.POSITION_BOTTOM_RIGHT + + +- **Use position constants** — Always use `CometChat.CallSettings.POSITION_*` constants instead of raw strings for positioning parameters. +- **Test all aspect ratios** — Try both `ASPECT_RATIO_CONTAIN` and `ASPECT_RATIO_COVER` to see which works best for your layout. +- **Keep name labels visible** — Name labels help users identify participants. Only hide them if your UI provides an alternative way to show participant names. +- **Apply settings before starting the call** — Pass the `MainVideoContainerSetting` object to `CallSettingsBuilder` before calling `startCall()`. + + + +- **Settings not applied** — Ensure you pass the `MainVideoContainerSetting` object to `setMainVideoContainerSetting()` on the `CallSettingsBuilder` before starting the call. +- **Full screen button not visible** — Check that `setFullScreenButtonParams()` has `visibility` set to `true` and the position doesn't overlap with other UI elements. +- **Name label background color not changing** — Verify the color string format is correct (e.g., `"rgba(27, 27, 27, 0.4)"` or `"#1B1B1B"`). +- **Video aspect ratio looks wrong** — Try switching between `ASPECT_RATIO_CONTAIN` (shows full video with letterboxing) and `ASPECT_RATIO_COVER` (fills container, may crop). + + +## Next Steps + + + + Implement standard audio and video calls + + + Start calls without a prior message + + + Add background blur and custom images to calls + + + Record audio and video calls + + + diff --git a/sdk/javascript/virtual-background.mdx b/sdk/javascript/virtual-background.mdx index 63edd0a8..7c21455d 100644 --- a/sdk/javascript/virtual-background.mdx +++ b/sdk/javascript/virtual-background.mdx @@ -1,9 +1,24 @@ --- title: "Virtual Background" +description: "Implement virtual background features in CometChat video calls including background blur, custom images, and user-configurable settings." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Apply background blur +const callController = CometChat.CallController.getInstance(); +callController.setBackgroundBlur(1); // blur level 1-99 +// Set background image +callController.setBackgroundImage("https://example.com/bg.jpg"); + +// Open virtual background settings UI +callController.openVirtualBackground(); +``` + This section will guide you to implement virtual background feature in video calls. ## Implementation @@ -114,3 +129,37 @@ The `VirtualBackground` Class is the required in case you want to change how the | `setImages(images: Array)` | This method allows developer to add their custom background image which the end user can choose. | | `enforceBackgroundBlur(enforceBackgroundBlur: number)` | This method starts the call with background blurred. To blur the background you need to pass an integer value between 1-99 which decides the blur level. **Default = 0** | | `enforceBackgroundImage(enforceBackgroundImage: string)` | This methods starts the call with the provided background image. | + + +- **Use `enforceBackgroundBlur` for privacy** — If your app requires background privacy (e.g., healthcare, finance), enforce blur at the settings level so users can't disable it. +- **Provide default images** — Use `setImages()` to provide a curated set of background images so users have good options without uploading their own. +- **Test blur levels** — Blur levels range from 1–99. Test different values to find the right balance between privacy and visual quality for your use case. +- **Optimize image URLs** — Use compressed images for custom backgrounds. Large images can slow down rendering and increase bandwidth usage. +- **Combine with CallSettings** — Pass the `VirtualBackground` object to `CallSettingsBuilder.setVirtualBackground()` to apply settings before the call starts. + + + +- **Virtual background not appearing** — Ensure the Calls SDK is properly initialized and the call is active before calling `setBackgroundBlur()` or `setBackgroundImage()`. +- **`openVirtualBackground()` does nothing** — The call must be active and the default layout must be enabled for the settings popup to appear. +- **Background image not loading** — Verify the image URL is accessible (CORS-enabled) and the image format is supported (JPEG, PNG). +- **Performance issues with blur** — High blur levels (close to 99) require more processing power. Lower the blur level on less powerful devices. +- **Settings not persisting between calls** — Virtual background settings are per-session. Use `enforceBackgroundBlur()` or `enforceBackgroundImage()` in `VirtualBackground` to apply defaults automatically. + + +## Next Steps + + + + Customize the main video container layout + + + Implement standard audio and video calls + + + Start calls without a prior message + + + Enable screen sharing and presenter features + + +