WebSocket: message event
The message event is fired when data is received through a WebSocket.
Syntax
Use the event name in methods like addEventListener(), or set an event handler property.
addEventListener('message', event => { })
onmessage = event => { }
Event type
An MessageEvent. Inherits from Event.
Event properties
In addition to the properties listed below, properties from the parent interface, Event, are available.
dataRead only-
The data sent by the message emitter.
originRead only-
A
USVStringrepresenting the origin of the message emitter. lastEventIdRead only-
A
DOMStringrepresenting a unique ID for the event. sourceRead only-
A
MessageEventSource(which can be aWindow,MessagePort, orServiceWorkerobject) representing the message emitter. portsRead only-
An array of
MessagePortobjects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).
Examples
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
Specifications
| Specification |
|---|
| HTML Standard # event-message |
| HTML Standard # handler-websocket-onmessage |
Browser compatibility
BCD tables only load in the browser