How do I tell the type of websocket onmessage's parameter?

19,396

Solution 1

The appropriate two types of frames that a server can send are text frames and binary frames (5.2). The ws.binaryType allows you to define in which format you'd like to obtain the binary data.

  • Binary data: depending on binaryType being set to either arraybuffer or blob
  • Text data: string

To determine the type, you can use:

  • e.data instanceof ArrayBuffer
  • e.data instanceof Blob
  • typeof e.data === "string"

Reference:

4. If type indicates that the data is Text, then initialize event's data attribute to data.

If type indicates that the data is Binary, and binaryType is set to "blob", then initialize event's data attribute to a new Blob object that represents data as its raw data.

If type indicates that the data is Binary, and binaryType is set to "arraybuffer", then initialize event's data attribute to a new read-only ArrayBuffer object whose contents are data.

Solution 2

"How do I tell it which type I want?"

The type of the data in a websocket frame is determined by the sender (see 1.2) and hence cannot be set by the receiver. If textual data is sent, then the type of e.data is string. If binary data is sent, then e.data will be an instance of either ArrayBuffer, or Blob, depending on the value of the ws.binaryType property set by the receiver.

"Or how do I know which type I get?"

This has already been answered by pimvdb.

Share:
19,396

Related videos on Youtube

marc40000
Author by

marc40000

:)

Updated on August 26, 2020

Comments