Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. WebSocket
  4. message

WebSocket: message event

Baseline Widely available

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 inWeb Workers.

Themessage event is fired when data is received through aWebSocket.

Syntax

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

js
addEventListener("message", (event) => { })onmessage = (event) => { }

Event type

AMessageEvent. Inherits fromEvent.

Event MessageEvent

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. The type of this property depends on the type of the WebSocket message and the value ofWebSocket.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 thebinaryType of this socket:
    • ArrayBuffer ifbinaryType is"arraybuffer",
    • Blob ifbinaryType is"blob". This does not have an associated media type (Blob.type is"").
originRead only

A string representing the origin of the message emitter.

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

Examples

js
// Create WebSocket connection.const socket = new WebSocket("ws://localhost:8080");// Listen for messagessocket.addEventListener("message", (event) => {  console.log("Message from server ", event.data);});

Specifications

Specification
WebSockets
# dom-websocket-onmessage

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp