Skip to content

MessageEvent ​

MessageEvent represents a message that was received.

The message event of WebSocket is one: data is the content of the message, and origin is the origin of the connection URL.

Inheritance: Event → MessageEvent

Constructor ​

MessageEvent()

Creates a MessageEvent. The runtime creates one itself when it fires the events below; app code can use it to build an event object and fire it with dispatchEvent() to try out a listener.

Instance properties ​

Also inherits the properties of Event; the most commonly used are type and target. The properties below are read-only; assigning to them throws TypeError.

PropertyDescription
data read-onlyThe content of the message
origin read-onlyThe origin of the sender
lastEventId read-onlyThe ID of the message. Always an empty string in messages the runtime fires
source read-onlyAlways null
ports read-onlyAlways an empty array

These properties live on the prototype, not on the event object itself: Object.keys(event) and { ...event } don't include them, so read them one by one. See Events with fields.

Events that use this class ​

ObjectEvents
WebSocketmessage

It can't be canceled: cancelable is false, and preventDefault() has no effect.

Examples ​

js
const ws = new WebSocket('wss://echo.websocket.org');
ws.addEventListener('open', () => ws.send('你好'));
ws.addEventListener('message', (e) => {
  console.log(e instanceof MessageEvent, e.origin, e.data);
});

Effect: once the connection opens it sends 你好; when the echo arrives, it prints true wss://echo.websocket.org and the content received. The value of origin is not verified in the simulator.

Corresponding iOS API ​

There is no corresponding system API. It corresponds to MessageEvent in the browser. A WebSocket message is the system's NSURLSessionWebSocketMessage, and its string or data is the data here.

See also ​