CloseEvent

interface

interface CloseEvent extends Event

The CloseEvent interface represents an event that occurs when a WebSocket connection is closed.

This event is sent to the client when the connection is closed, providing information about why the connection was closed through the code, reason, and wasClean properties.

Example

// Handling a close event
ws.addEventListener("close", (event: CloseEvent) => {
  console.log(`Connection closed with code ${event.code}`);
  console.log(`Reason: ${event.reason}`);
  console.log(`Clean close: ${event.wasClean}`);

  if (event.code === 1006) {
    console.log("Connection closed abnormally");
  }
});

See also

variable

var CloseEvent: { … }

Constructor interface for creating CloseEvent instances.

Example

// Creating a custom close event
const event = new CloseEvent("close", {
  code: 1000,
  reason: "Normal closure",
  wasClean: true,
});

// Dispatching the event
myWebSocket.dispatchEvent(event);

See also

Constructors

constructor

new CloseEvent(type: string, eventInitDict?: CloseEventInit): CloseEvent

Properties

code

readonly code: number

Returns the WebSocket connection close code provided by the server.

reason

readonly reason: string

Returns the WebSocket connection close reason provided by the server.

wasClean

readonly wasClean: boolean

Returns true if the connection closed cleanly; false otherwise.

prototype

readonly prototype: CloseEvent