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?
2 Answers
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 eitherarraybuffer
orblob
- Text data: string
To determine the type, you can use:
e.data instanceof ArrayBuffer
e.data instanceof Blob
typeof e.data === "string"
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'sdata
attribute to a newBlob
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'sdata
attribute to a new read-onlyArrayBuffer
object whose contents aredata
.
"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.