Monitor real-time WebSocket connection status and respond to connectivity changes using the CometChat JavaScript SDK.
AI Integration Quick Reference
// Get current status: "connecting" | "connected" | "disconnected"const status = CometChat.getConnectionStatus();// Listen for connection changesCometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({ onConnected: () => console.log("Connected"), inConnecting: () => console.log("Connecting..."), onDisconnected: () => console.log("Disconnected")}));// CleanupCometChat.removeConnectionListener("LISTENER_ID");
The CometChat SDK maintains a WebSocket connection to CometChat servers for real-time events. You can check the current connection state and listen for changes — useful for showing connectivity indicators in your UI or queuing operations while offline.When the connection drops, the SDK automatically attempts to reconnect, cycling through disconnected → connecting → connected.
Register a ConnectionListener to receive real-time connection state updates. We recommend adding this on app startup after CometChat.init() completes.
TypeScript
JavaScript
let listenerID: string = "UNIQUE_LISTENER_ID";CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ onConnected: () => { console.log("ConnectionListener => On Connected"); }, inConnecting: () => { console.log("ConnectionListener => In connecting"); }, onDisconnected: () => { console.log("ConnectionListener => On Disconnected"); }, }));
let listenerID = "UNIQUE_LISTENER_ID";CometChat.addConnectionListener( listenerID, new CometChat.ConnectionListener({ onConnected: () => { console.log("ConnectionListener => On Connected"); }, inConnecting: () => { console.log("ConnectionListener => In connecting"); }, onDisconnected: () => { console.log("ConnectionListener => On 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.