30

Here https://developer.mozilla.org/en/WebSockets/WebSockets_reference/MessageEvent it states attribute data is of type DOMString| Blob | ArrayBuffer. How do I tell it which type I want? Or how do I know which type I get?

marc40000
  • 3,167
  • 9
  • 41
  • 63

2 Answers2

51

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.

Community
  • 1
  • 1
pimvdb
  • 151,816
  • 78
  • 307
  • 352
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.

Community
  • 1
  • 1
Chris
  • 1,335
  • 10
  • 19