Browser WebSocket APILesson 2.1
How to open a WebSocket connection from the browser
WebSocket constructor, ws:// vs wss:// URLs, passing subprotocols, onopen callback, readyState guard, same-origin vs cross-origin connections
Creating Your First WebSocket Connection
The browser WebSocket API is a single constructor with four event handlers. Here is the minimal setup:
const ws = new WebSocket('wss://api.example.com/ws');
ws.onopen = () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'hello' }));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log('Received:', msg);
};
ws.onerror = (err) => {
console.error('WebSocket error', err);
};
ws.onclose = (event) => {
console.log('Closed', event.code, event.reason);
};wss:// vs ws://
Always use wss:// (WebSocket Secure, TLS-wrapped) in production. Modern browsers block mixed content - a page served over HTTPS cannot open a plain ws:// connection. During local development, ws://localhost is fine because localhost is treated as a secure origin.
Subprotocols
Pass a string or array as the second argument to advertise supported subprotocols. The server selects one and echoes it in the Sec-WebSocket-Protocol response header. If no match, the server may reject. Use this to version your protocol:
const ws = new WebSocket('wss://api.example.com/ws', ['v2', 'v1']);
ws.onopen = () => {
console.log('Negotiated protocol:', ws.protocol);
};