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

marc40000 picture marc40000 · Feb 27, 2012 · Viewed 17k times · Source

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?

Answer

pimvdb picture pimvdb · Feb 27, 2012

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.