Skip to main content

Signature

function websocket(options: WebSocketOptions): Promise<WebSocket>

Options

url
string
required
WebSocket URL. Must start with ws:// or wss://.
browser
BrowserProfile
Browser fingerprint profile to use for the connection.
os
EmulationOS
Operating system to emulate.
proxy
string
Proxy URL for the WebSocket connection.
headers
Record<string, string>
Additional headers for the WebSocket handshake.
onMessage
(data: string | Uint8Array) => void
Callback for incoming messages.
onClose
() => void
Callback when the connection closes.
onError
(error: Error) => void
Callback for connection errors.

WebSocket object

The returned WebSocket object has:

ws.send(data)

Send a message to the server.
await ws.send('Hello, server!');
await ws.send(JSON.stringify({ type: 'ping' }));

ws.close()

Close the WebSocket connection.
await ws.close();

Examples

Basic connection

import { websocket } from 'wreq-js';

const ws = await websocket({
  url: 'wss://echo.websocket.org',
  browser: 'chrome_142',
  onMessage: (data) => {
    console.log('Received:', data);
  },
});

await ws.send('Hello!');

// Later...
await ws.close();

With all callbacks

const ws = await websocket({
  url: 'wss://example.com/socket',
  browser: 'chrome_142',
  headers: {
    'Authorization': 'Bearer token123',
  },
  onMessage: (data) => {
    if (typeof data === 'string') {
      console.log('Text message:', data);
    } else {
      console.log('Binary message:', data.byteLength, 'bytes');
    }
  },
  onClose: () => {
    console.log('Connection closed');
  },
  onError: (error) => {
    console.error('WebSocket error:', error.message);
  },
});

Through a proxy

const ws = await websocket({
  url: 'wss://example.com/socket',
  browser: 'chrome_142',
  proxy: 'http://user:[email protected]:8080',
  onMessage: (data) => console.log(data),
});

JSON messaging

const ws = await websocket({
  url: 'wss://api.example.com/ws',
  browser: 'chrome_142',
  onMessage: (data) => {
    if (typeof data === 'string') {
      const message = JSON.parse(data);
      
      switch (message.type) {
        case 'pong':
          console.log('Server responded to ping');
          break;
        case 'data':
          console.log('Received data:', message.payload);
          break;
      }
    }
  },
});

// Send JSON messages
await ws.send(JSON.stringify({ type: 'ping' }));
await ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));