6.6 KiB
WebSocket Manager Console API Documentation
The WebSocket Manager provides a browser console interface for interactive testing and debugging of WebSocket connections. When the application loads, the manager is automatically exposed to the global window
object.
Quick Start
Open your browser's developer console and you'll see initialization messages:
🚀 WebSocket Manager exposed to console!
📖 Use 'wsHelp' to see available commands
🔧 Access manager via 'wsManager'
Global Objects
wsManager
The main WebSocket manager instance with all functionality.
wsHelp
Quick reference object containing usage examples for all commands.
API Reference
Connection Status
wsManager.getServerUrls()
Returns an array of all configured server URLs.
Returns: Array<string>
Example:
wsManager.getServerUrls()
// Returns: ["ws://localhost:8080", "ws://localhost:8081", "ws://localhost:8443/ws"]
wsManager.getConnectionStatuses()
Returns an object mapping each server URL to its current connection status.
Returns: Object<string, string>
Possible Status Values:
"Connected"
- WebSocket is connected and ready"Disconnected"
- WebSocket is not connected
Example:
wsManager.getConnectionStatuses()
// Returns: {
// "ws://localhost:8080": "Disconnected",
// "ws://localhost:8081": "Disconnected",
// "ws://localhost:8443/ws": "Connected"
// }
wsManager.isConnected(url)
Check if a specific server is connected.
Parameters:
url
(string) - The WebSocket server URL to check
Returns: boolean
Example:
wsManager.isConnected('ws://localhost:8443/ws')
// Returns: true or false
wsManager.getConnectionCount()
Get the total number of configured servers (not necessarily connected).
Returns: number
Example:
wsManager.getConnectionCount()
// Returns: 3
Script Execution
wsManager.executeScript(url, script)
Execute a Rhai script on a specific connected server.
Parameters:
url
(string) - The WebSocket server URLscript
(string) - The Rhai script to execute
Returns: Promise<string>
- Resolves with script output or rejects with error
Example:
// Simple calculation
await wsManager.executeScript('ws://localhost:8443/ws', 'let x = 42; `Result: ${x}`')
// Get current timestamp
await wsManager.executeScript('ws://localhost:8443/ws', '`Current time: ${new Date().toISOString()}`')
// JSON response
await wsManager.executeScript('ws://localhost:8443/ws', `
let data = #{
message: "Hello from WebSocket!",
value: 42,
timestamp: new Date().toISOString()
};
to_json(data)
`)
wsManager.executeScriptOnAll(script)
Execute a Rhai script on all connected servers simultaneously.
Parameters:
script
(string) - The Rhai script to execute
Returns: Promise<Object>
- Object mapping URLs to their results
Example:
// Get server info from all connected servers
const results = await wsManager.executeScriptOnAll('`Server response from: ${new Date().toISOString()}`')
console.log(results)
// Returns: {
// "ws://localhost:8443/ws": "Server response from: 2025-01-16T14:30:00.000Z",
// "ws://localhost:8080": "Error: Connection failed",
// "ws://localhost:8081": "Error: Connection failed"
// }
Connection Management
wsManager.reconnect()
Attempt to reconnect to all configured servers.
Returns: Promise<string>
- Success or error message
Example:
await wsManager.reconnect()
// Console output: "Reconnected to servers"
Rhai Script Examples
The WebSocket servers execute Rhai scripts. Here are some useful examples:
Basic Operations
// Simple calculation
await wsManager.executeScript(url, 'let result = 2 + 2; `2 + 2 = ${result}`')
// String manipulation
await wsManager.executeScript(url, 'let msg = "Hello"; `${msg.to_upper()} WORLD!`')
// Current timestamp
await wsManager.executeScript(url, '`Current time: ${new Date().toISOString()}`')
JSON Data
// Create and return JSON
await wsManager.executeScript(url, `
let data = #{
id: 123,
name: "Test User",
active: true,
created: new Date().toISOString()
};
to_json(data)
`)
Conditional Logic
// Conditional responses
await wsManager.executeScript(url, `
let hour = new Date().getHours();
if hour < 12 {
"Good morning!"
} else if hour < 18 {
"Good afternoon!"
} else {
"Good evening!"
}
`)
Loops and Arrays
// Generate data with loops
await wsManager.executeScript(url, `
let numbers = [];
for i in 1..6 {
numbers.push(i * i);
}
\`Squares: \${numbers}\`
`)
Error Handling
All async operations return Promises that can be caught:
try {
const result = await wsManager.executeScript('ws://localhost:8080', 'let x = 42; x');
console.log('Success:', result);
} catch (error) {
console.error('Script failed:', error);
}
Common error scenarios:
- Connection Error: Server is not connected
- Script Error: Invalid Rhai syntax or runtime error
- Timeout: Script execution took too long
- Network Error: WebSocket connection lost
Console Logging
The manager automatically logs important events to the console:
- ✅ Success messages: Script execution completed
- ❌ Error messages: Connection failures, script errors
- 🔄 Status updates: Reconnection attempts
- 📡 Network events: WebSocket state changes
Development Tips
-
Check Connection Status First:
wsManager.getConnectionStatuses()
-
Test Simple Scripts First:
await wsManager.executeScript(url, '"Hello World"')
-
Use Template Literals for Complex Scripts:
const script = ` let data = #{ timestamp: new Date().toISOString(), random: Math.random() }; to_json(data) `; await wsManager.executeScript(url, script)
-
Monitor Console for Detailed Logs: The manager provides detailed logging for debugging connection and execution issues.
Integration with UI
The console API shares the same WebSocket manager instance as the web UI, so:
- Connection status changes are reflected in both
- Scripts executed via console appear in the UI responses
- Authentication state is shared between console and UI
This makes the console API perfect for:
- Development: Quick script testing
- Debugging: Connection troubleshooting
- Automation: Batch operations
- Learning: Exploring Rhai script capabilities