JavaScript SDK
JavaScript SDK
Section titled “JavaScript SDK”The Jetsocket JavaScript client library supports web browsers, web workers, and Node.js environments.
Installation
Section titled “Installation”Web (Browser)
Section titled “Web (Browser)”Via CDN
Section titled “Via CDN”<script src="https://js.jetsocket.io/latest/jetsocket.min.js"></script>Via NPM
Section titled “Via NPM”npm install jetsocket-jsimport Jetsocket from 'jetsocket-js';Encrypted Channel Support
Section titled “Encrypted Channel Support”For encrypted channels, use the encryption-enabled build:
<script src="https://js.jetsocket.io/latest/jetsocket-with-encryption.min.js"></script>import Jetsocket from 'jetsocket-js/with-encryption';Node.js
Section titled “Node.js”npm install jetsocket-jsconst Jetsocket = require('jetsocket-js');Web Workers
Section titled “Web Workers”importScripts('https://js.jetsocket.io/latest/jetsocket.worker.min.js');Or with a bundler:
import Jetsocket from 'jetsocket-js/worker';Initialization
Section titled “Initialization”const jetsocket = new Jetsocket(APP_KEY, { cluster: APP_CLUSTER,});Configuration Options
Section titled “Configuration Options”const jetsocket = new Jetsocket(APP_KEY, { cluster: APP_CLUSTER, forceTLS: true, channelAuthorization: { endpoint: '/jetsocket/auth', transport: 'ajax' }, userAuthentication: { endpoint: '/jetsocket/user-auth', transport: 'ajax' }, wsHost: 'ws.jetsocket.io', wsPort: 443, wssPort: 443, httpHost: 'sockjs.jetsocket.io', httpPort: 80, httpsPort: 443, httpPath: '/jetsocket', statsHost: 'stats.jetsocket.io', activityTimeout: 30000, pongTimeout: 15000, maxReconnectionAttempts: 6, maxReconnectGap: 10000, enableLogging: false, ignoreNullOrigin: false, enableStats: true, auth: { headers: { 'X-Custom-Header': 'value' } }});Configuration Parameters
Section titled “Configuration Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
cluster | String | - | Your Jetsocket cluster |
forceTLS | Boolean | true | Force TLS connections |
channelAuthorization.endpoint | String | /jetsocket/auth | Authorization endpoint |
channelAuthorization.transport | String | ajax | Transport method (ajax or jsonp) |
userAuthentication.endpoint | String | /jetsocket/user-auth | User authentication endpoint |
wsHost | String | ws.jetsocket.io | WebSocket host |
wsPort | Number | 443 | WebSocket port |
wssPort | Number | 443 | WebSocket secure port |
activityTimeout | Number | 30000 | Connection timeout |
pongTimeout | Number | 15000 | Pong timeout |
maxReconnectionAttempts | Number | 6 | Max reconnection attempts |
enableLogging | Boolean | false | Enable debug logging |
Connection Management
Section titled “Connection Management”Connection Events
Section titled “Connection Events”jetsocket.connection.bind('connected', () => { console.log('Connected to Jetsocket');});
jetsocket.connection.bind('disconnected', () => { console.log('Disconnected from Jetsocket');});
jetsocket.connection.bind('error', (error) => { console.error('Connection error:', error);});
jetsocket.connection.bind('state_change', (states) => { console.log('Connection state changed from', states.previous, 'to', states.current);});Connection State
Section titled “Connection State”console.log(jetsocket.connection.state); // 'connected', 'connecting', 'disconnected', 'failed'console.log(jetsocket.connection.connected); // true/falseSocket ID
Section titled “Socket ID”jetsocket.connection.bind('connected', () => { console.log('Socket ID:', jetsocket.connection.socket_id);});Channel Management
Section titled “Channel Management”Subscribing to Channels
Section titled “Subscribing to Channels”// Public channelconst publicChannel = jetsocket.subscribe('my-channel');
// Private channelconst privateChannel = jetsocket.subscribe('private-my-channel');
// Presence channelconst presenceChannel = jetsocket.subscribe('presence-my-channel');
// Encrypted channelconst encryptedChannel = jetsocket.subscribe('private-encrypted-my-channel');Channel Events
Section titled “Channel Events”const channel = jetsocket.subscribe('my-channel');
channel.bind('jetsocket:subscription_succeeded', () => { console.log('Successfully subscribed to channel');});
channel.bind('jetsocket:subscription_error', (error) => { console.error('Subscription error:', error);});Unsubscribing
Section titled “Unsubscribing”jetsocket.unsubscribe('my-channel');Accessing Channels
Section titled “Accessing Channels”// Get a specific channelconst channel = jetsocket.channel('my-channel');
// Get all subscribed channelsconst allChannels = jetsocket.allChannels();allChannels.forEach(channel => { console.log('Subscribed to:', channel.name);});Event Handling
Section titled “Event Handling”Binding to Events
Section titled “Binding to Events”const channel = jetsocket.subscribe('my-channel');
// Bind to specific eventchannel.bind('new-message', (data) => { console.log('New message:', data);});
// Bind with contextchannel.bind('my-event', function() { console.log('Hello', this.name);}, { name: 'Jetsocket' });
// Bind to all eventschannel.bind_global((eventName, data) => { console.log(`Event ${eventName}:`, data);});Unbinding Events
Section titled “Unbinding Events”const handler = (data) => console.log(data);
// Bind eventchannel.bind('my-event', handler);
// Unbind specific handlerchannel.unbind('my-event', handler);
// Unbind all handlers for an eventchannel.unbind('my-event');
// Unbind all eventschannel.unbind();
// Unbind all global handlerschannel.unbind_global();
// Unbind everythingchannel.unbind_all();Client Events
Section titled “Client Events”Client events can only be triggered on private and presence channels:
const channel = jetsocket.subscribe('private-my-channel');
// Trigger client eventchannel.trigger('client-my-event', { message: 'Hello from client!' });
// Listen for client eventschannel.bind('client-my-event', (data, metadata) => { console.log('Client event from', metadata.user_id, ':', data);});Presence Channels
Section titled “Presence Channels”Basic Usage
Section titled “Basic Usage”const presenceChannel = jetsocket.subscribe('presence-my-channel');
presenceChannel.bind('jetsocket:subscription_succeeded', (members) => { console.log('Current members:', members);});
presenceChannel.bind('jetsocket:member_added', (member) => { console.log('Member joined:', member);});
presenceChannel.bind('jetsocket:member_removed', (member) => { console.log('Member left:', member);});Member Information
Section titled “Member Information”presenceChannel.bind('jetsocket:subscription_succeeded', (members) => { // Get member count console.log('Member count:', presenceChannel.members.count);
// Get all members const allMembers = presenceChannel.members.members;
// Check if specific user is present const isPresent = presenceChannel.members.get('user-123');
// Get member info if (isPresent) { console.log('User info:', isPresent.info); }});Error Handling
Section titled “Error Handling”Connection Errors
Section titled “Connection Errors”jetsocket.connection.bind('error', (error) => { console.error('Connection error:', error);
// Handle specific error types if (error.type === 'WebSocketError') { console.log('WebSocket connection failed'); } else if (error.type === 'HTTPError') { console.log('HTTP connection failed'); }});Channel Errors
Section titled “Channel Errors”const channel = jetsocket.subscribe('private-my-channel');
channel.bind('jetsocket:subscription_error', (error) => { console.error('Subscription error:', error);
if (error.status === 403) { console.log('Access denied to channel'); } else if (error.status === 404) { console.log('Channel not found'); }});Global Error Handling
Section titled “Global Error Handling”jetsocket.bind_global((eventName, data) => { if (eventName === 'jetsocket:error') { console.error('Global error:', data); }});Utility Methods
Section titled “Utility Methods”Connection State
Section titled “Connection State”// Check if connectedif (jetsocket.connection.connected) { console.log('Connected');}
// Get connection stateconsole.log(jetsocket.connection.state);
// Get socket IDconsole.log(jetsocket.connection.socket_id);Channel Utilities
Section titled “Channel Utilities”// Check if subscribed to channelconst channel = jetsocket.channel('my-channel');console.log(channel.subscribed);
// Get channel nameconsole.log(channel.name);
// Get all channelsconst channels = jetsocket.allChannels();Browser Compatibility
Section titled “Browser Compatibility”The Jetsocket JavaScript library supports:
- Chrome: 16+
- Firefox: 11+
- Safari: 7+
- Edge: 12+
- Internet Explorer: 10+ (with polyfills)
TypeScript Support
Section titled “TypeScript Support”import Jetsocket from 'jetsocket-js';import * as JetsocketTypes from 'jetsocket-js';
const jetsocket: JetsocketTypes.Jetsocket = new Jetsocket("APP_KEY", { cluster: "APP_CLUSTER",});
const channel: JetsocketTypes.Channel = jetsocket.subscribe('my-channel');const presenceChannel: JetsocketTypes.PresenceChannel = jetsocket.subscribe('presence-my-channel');Examples
Section titled “Examples”Complete Chat Application
Section titled “Complete Chat Application”<!DOCTYPE html><html><head> <script src="https://js.jetsocket.io/latest/jetsocket.min.js"></script></head><body> <div id="messages"></div> <input type="text" id="messageInput" placeholder="Type a message..."> <button onclick="sendMessage()">Send</button>
<script> const jetsocket = new Jetsocket("APP_KEY", { cluster: "APP_CLUSTER", });
const channel = jetsocket.subscribe("chat-room"); const messagesDiv = document.getElementById("messages");
// Connection events jetsocket.connection.bind('connected', () => { console.log('Connected to Jetsocket'); });
jetsocket.connection.bind('error', (error) => { console.error('Connection error:', error); });
// Channel events channel.bind('jetsocket:subscription_succeeded', () => { console.log('Subscribed to chat room'); });
channel.bind('new-message', (data) => { const messageElement = document.createElement("div"); messageElement.textContent = `${data.username}: ${data.message}`; messagesDiv.appendChild(messageElement); });
function sendMessage() { const input = document.getElementById("messageInput"); const message = input.value;
if (message.trim()) { // Send to server fetch("/send-message", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message }) });
input.value = ""; } } </script></body></html>Next Steps
Section titled “Next Steps”- Learn about channels and different channel types
- Explore authentication for secure applications
- Check out server libraries for backend integration