Skip to main content

Client API Reference

The WSX client provides a JavaScript API for interacting with WSX servers, sending requests, and handling responses.

WSX Client Class

Constructor

Parameters

  • options (Object): Configuration options
    • url (string): WebSocket server URL
    • autoConnect (boolean): Auto-connect on instantiation (default: true)
    • reconnect (boolean): Auto-reconnect on connection loss (default: true)
    • reconnectInterval (number): Reconnection interval in ms (default: 3000)
    • maxReconnectAttempts (number): Maximum reconnection attempts (default: 10)
    • debug (boolean): Enable debug logging (default: false)

Example

Connection Methods

connect()

Establishes a WebSocket connection to the server.

Returns

  • Promise<void>: Resolves when connection is established

Example

disconnect()

Closes the WebSocket connection.

Example

isConnected()

Checks if the client is currently connected.

Returns

  • boolean: true if connected, false otherwise

Example

Request Methods

send()

Sends a request to the server.

Parameters

  • handler (string): Handler name on the server
  • target (string): CSS selector for the target element
  • data (Object): Data to send with the request (optional)
  • options (Object): Request options (optional)
    • swap (string): How to swap the response content
    • trigger (string): Trigger information
    • timeout (number): Request timeout in ms

Returns

  • Promise<WSXResponse>: Promise that resolves with the server response

Example

sendForm()

Sends form data to the server.

Parameters

  • handler (string): Handler name on the server
  • target (string): CSS selector for the target element
  • formElement (HTMLFormElement): Form element to serialize
  • options (Object): Request options (optional)

Returns

  • Promise<WSXResponse>: Promise that resolves with the server response

Example

sendFile()

Sends a file to the server.

Parameters

  • handler (string): Handler name on the server
  • target (string): CSS selector for the target element
  • file (File): File to upload
  • options (Object): Request options (optional)
    • onProgress (Function): Progress callback function

Returns

  • Promise<WSXResponse>: Promise that resolves with the server response

Example

Data Channel Methods

sendJson()

Send a JSON payload to the server on a named channel.

Parameters

  • channel (string): Logical channel name shared with the server
  • data (*): JSON-serializable payload
  • options (Object, optional): Additional options
    • id (string): Explicit message identifier
    • metadata (Object): Extra metadata forwarded untouched

Returns

  • string: Identifier assigned to the message

Example

onJson()

Register a handler for JSON messages. Accepts either a channel/handler pair or a catch-all handler.

Parameters

  • channel (string|function): Channel to listen on, or the handler for catch-all usage
  • handler (function, optional): Callback receiving { id, channel, data, metadata }

Returns

  • WSX: The client instance for chaining

Example

offJson()

Remove JSON handlers.

Parameters

  • channel (string, optional): Channel to remove; omit to clear all JSON handlers

Returns

  • WSX: The client instance

Example

sendStream()

Send a binary payload to the server on a named stream channel.

Parameters

  • channel (string): Stream channel name
  • payload (ArrayBuffer|ArrayBufferView|Blob): Binary data to transmit
  • options (Object, optional): Additional options
    • id (string): Explicit stream identifier
    • metadata (Object): Metadata forwarded with the frame

Returns

  • Promise<string>: Resolves with the stream identifier

Example

onStream()

Register a handler for incoming binary stream frames.

Parameters

  • channel (string|function): Channel to observe, or the catch-all handler
  • handler (function, optional): Callback receiving { id, channel, metadata, data, arrayBuffer }

Returns

  • WSX: The client instance

Example

offStream()

Remove stream handlers.

Parameters

  • channel (string, optional): Channel to remove; omit to clear all stream handlers

Returns

  • WSX: The client instance

Example

Event Handling

on()

Registers an event listener.

Parameters

  • event (string): Event name
  • callback (Function): Event handler function

Events

  • connect: Fired when connection is established
  • disconnect: Fired when connection is closed
  • message: Fired when a message is received
  • error: Fired when an error occurs
  • reconnect: Fired when reconnection starts
  • reconnected: Fired when reconnection succeeds

Example

off()

Removes an event listener.

Parameters

  • event (string): Event name
  • callback (Function): Event handler function to remove

Example

once()

Registers a one-time event listener.

Parameters

  • event (string): Event name
  • callback (Function): Event handler function

Example

DOM Integration

processResponse()

Processes a server response and updates the DOM.

Parameters

  • response (WSXResponse): Server response object

Example

swapContent()

Swaps content in a target element.

Parameters

  • target (string|HTMLElement): Target element or selector
  • html (string): HTML content to swap
  • swapType (string): How to swap the content

Swap Types

  • innerHTML: Replace element’s inner HTML
  • outerHTML: Replace the entire element
  • beforebegin: Insert before the element
  • afterbegin: Insert as first child
  • beforeend: Insert as last child
  • afterend: Insert after the element

Example

Utility Methods

generateId()

Generates a unique request ID.

Returns

  • string: Unique identifier

Example

serializeForm()

Serializes a form element to an object.

Parameters

  • formElement (HTMLFormElement): Form element to serialize

Returns

  • Object: Serialized form data

Example

parseSelector()

Parses a CSS selector and returns element information.

Parameters

  • selector (string): CSS selector

Returns

  • Object: Parsed selector information

Example

Configuration Methods

setConfig()

Updates client configuration.

Parameters

  • options (Object): Configuration options to update

Example

getConfig()

Gets current client configuration.

Returns

  • Object: Current configuration

Example

Request Queue Methods

getQueueSize()

Gets the current request queue size.

Returns

  • number: Number of queued requests

Example

clearQueue()

Clears the request queue.

Example

Static Methods

WSX.create()

Creates a new WSX instance with default configuration.

Parameters

  • url (string): WebSocket server URL
  • options (Object): Configuration options (optional)

Returns

  • WSX: New WSX instance

Example

WSX.version

Gets the WSX client version.

Returns

  • string: Version string

Example

Error Handling

WSXError

Base error class for WSX-related errors.

Properties

  • message (string): Error message
  • code (string): Error code
  • details (Object): Additional error details

Example

ConnectionError

Error thrown when connection fails.

TimeoutError

Error thrown when request times out.

ValidationError

Error thrown when request validation fails.

HTML Attributes

wx-config

Configures WSX for a page or element.

wx-send

Specifies the handler to call when triggered.

wx-target

Specifies the target element for the response.

wx-trigger

Specifies when to trigger the request.

wx-swap

Specifies how to swap the response content.

wx-include

Specifies what data to include with the request.

wx-confirm

Shows a confirmation dialog before sending the request.

wx-disable

Disables the element while the request is in progress.

wx-indicator

Shows a loading indicator while the request is in progress.

Global Functions

window.wsx

Global WSX instance created automatically when WSX is initialized with HTML attributes.

Example

wx()

Shorthand function for accessing the global WSX instance.

Data Channel Types

WSXJSONOptions

Optional configuration when sending JSON messages.

WSXStreamOptions

Optional configuration for binary stream frames.

WSXJSONDetail

Structure delivered to JSON handlers and DOM events.

WSXStreamDetail

Structure delivered to stream handlers and DOM events.

Best Practices

  1. Error Handling: Always wrap WSX calls in try-catch blocks
  2. Event Cleanup: Remove event listeners when no longer needed
  3. Connection Management: Handle connection state changes appropriately
  4. Request Queuing: Monitor queue size to prevent memory issues
  5. Performance: Use appropriate swap types for optimal DOM updates
  6. Security: Validate and sanitize all data before sending
  7. Accessibility: Ensure dynamic content updates are accessible

Browser Compatibility

WSX client supports:
  • Chrome 60+
  • Firefox 55+
  • Safari 11+
  • Edge 79+
For older browsers, consider using polyfills for:
  • WebSocket
  • Promise
  • fetch API

Next Steps