C.W.K.
Stream
Lesson 02 of 08 · published

Connection Events

~11 min · browser, events

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Four events, that is the whole API

The browser WebSocket exposes exactly four events: open, message, error, and close. You can wire them via on* properties (one handler each) or via addEventListener (multiple handlers, recommended). There is no connecting event, no reconnect event, no pong event — those are all things you build yourself.

Firing order

For a normal session: open → message* → close. For a failed handshake: error → close. For a runtime drop: ...message → error → close. Critically, error always fires before close, and error deliberately does not expose much — for security, the browser does not leak why the connection failed. To learn the close code and reason, look at the close event.

What you receive

event.data in message can be a string (text frames), a Blob (default for binary), or an ArrayBuffer (if you set ws.binaryType = 'arraybuffer'). event.code, event.reason, and event.wasClean on the close event tell you how it ended.

Code

Wiring all four events·javascript
const ws = new WebSocket('wss://api.example.com/ws');

ws.addEventListener('open', () => {
  console.log('connected, sending greeting');
  ws.send(JSON.stringify({ type: 'hello' }));
});

ws.addEventListener('message', (event) => {
  // event.data: string | Blob | ArrayBuffer
  if (typeof event.data === 'string') {
    console.log('text:', event.data);
  } else {
    console.log('binary frame, bytes:', event.data.size ?? event.data.byteLength);
  }
});

ws.addEventListener('error', () => {
  // Deliberately opaque. Look at the close event for details.
  console.warn('ws error (details in close)');
});

ws.addEventListener('close', (event) => {
  console.log('closed', {
    code:     event.code,
    reason:   event.reason,
    wasClean: event.wasClean,
  });
});
Removing a listener properly·javascript
function onMessage(e) { console.log(e.data); }
ws.addEventListener('message', onMessage);
// later...
ws.removeEventListener('message', onMessage);

External links

Exercise

Build a tiny page with an <input> and a <pre>. On load, open a WebSocket to your favorite echo server. Wire all four events to append to the <pre> with a clear prefix ([open] / [msg] / [err] / [close 1006]). Force a disconnect by killing your wifi for 10 seconds. Read the resulting close code on screen.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.