⚡ WebSockets & Real-time
Beginner
What events does a WebSocket connection have?
Answer
The WebSocket API exposes four primary events: (1) open — fires when the connection is successfully established after the handshake; this is when you can safely start sending messages; (2) message — fires when a message is received from the server; the event object contains a data property with the message content (string or Blob); (3) error — fires when an error occurs; unfortunately, the browser intentionally provides minimal error details for security reasons; (4) close — fires when the connection is closed, with a code (WebSocket close code, e.g., 1000 for normal closure, 1006 for abnormal) and reason string. You can listen using either ws.onopen = handler or ws.addEventListener('open', handler).