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
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.
| Property | Description |
|---|---|
data read-only | The content of the message |
origin read-only | The origin of the sender |
lastEventId read-only | The ID of the message. Always an empty string in messages the runtime fires |
source read-only | Always null |
ports read-only | Always 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
| Object | Events |
|---|---|
WebSocket | message |
It can't be canceled: cancelable is false, and preventDefault() has no effect.
Examples
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
WebSocket: the object that fires this eventmessage: when it is fired- Sending and receiving messages with WebSocket