Video in progress
What are the main events of the browser WebSocket API?
Four: onopen (the connection is ready), onmessage (a message arrived), onerror (an error), onclose (the connection closed). You send with send() and close with close().
📖 Answer
const ws = new WebSocket('wss://example.uz/ws');
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'join', room: 'java' }));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
render(msg);
};
ws.onerror = (e) => console.error('ws xato', e);
ws.onclose = (e) => {
console.log('yopildi', e.code, e.reason);
};
A mistake beginners make a lot is calling send() right after new WebSocket(...). At that moment the connection is still CONNECTING and you get an InvalidStateError. Send inside onopen, or after checking ws.readyState === WebSocket.OPEN.
Another thing: onerror barely tells you why it failed (for security reasons). For details, look at the code in onclose and at the server logs.
The browser API has no automatic reconnect. You write it yourself or use a library.
Sign up to mark studied questions and save your progress.