This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available in Web Workers.
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) => { }
A MessageEvent. Inherits from Event.
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.
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:
lastEventId Read only
source Read only
ports Read only
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Listen for messages
socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
});
| Specification |
|---|
| WebSockets> # dom-websocket-onmessage> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
message_event |
5 | 12 | 7 | 12.1 | 5 | 18 | 7 | 12.1 | 4.2 | 1.0 | 4.4 | 4.2 |
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/message_event