WebSocket: message event

The message event is fired when data is received through a WebSocket.


Use the event name in methods like addEventListener(), or set an event handler property.

addEventListener("message", (event) => {});

onmessage = (event) => {};

Event type

Event properties

In addition to the properties listed below, properties from the parent interface, Event, are available.

data Read only

The data sent by the message emitter. The type of this property depends on the type of the WebSocket message and the value of WebSocket.binaryType.

  • If the message type is "text", then this field is a string.
  • If the message type is "binary" type, then the type of this property can be inferred from the binaryType of this socket:
    • ArrayBuffer if binaryType is "arraybuffer",
    • Blob if binaryType is "blob". This does not have an associated media type (Blob.type is "").
origin Read only

A string representing the origin of the message emitter.

Other properties from the MessageEvent interface are present, but do not pertain to the WebSocket API and are left at their default values:


// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");

// Listen for messages
socket.addEventListener("message", (event) => {
  console.log("Message from server ", event.data);


WebSockets Standard
# dom-websocket-onmessage

Browser compatibility

BCD tables only load in the browser

See also