Loading...
const ws = new WebSocket('wss://example.com/chat');
ws.send('hello');function connect() {
const ws = new WebSocket('wss://example.com/chat');
ws.addEventListener('open', () => ws.send('hello'));
ws.addEventListener('close', () => setTimeout(connect, 1000));
}
connect();Sending waits for the open event, and the socket reconnects after a delay when it closes.
send() right after creating the socket, before the open event.close and error, and the code reconnects with a delay.readyState equals WebSocket.OPEN.Use server-sent events when only the server sends updates. Use WebSocket when both sides send messages often.
No. The browser API cannot set headers, so pass auth through cookies, the first message, or a short-lived token in the URL.
Call ws.send(JSON.stringify(data)), and parse with JSON.parse(event.data) in the message handler.