How to read BLOB data from a WebSocket which is not an image

You can set tye binaryType of the WebSocket in JavaScript like:

var socket = new WebSocket(url);
socket.binaryType = "arraybuffer";

Or respectively in CoffeeScript

socket = new WebSocket url
socket.binaryType = "arraybuffer"

And you will get ArrayBuffers instead of Blobs. Convert them to Uint8Array by new Uint8Array(event.data);


you can also use Blob.text().

socket.addEventListener("message", event => {
    // event.data is Blob
    event.data.text().then(txt=>console.log(txt))   
});

Ok, I found the solution! I have to read the data that comes as a Blob with a FileReader:

socket = new WebSocket 'wss://myserverurl/some-endpoint'
socket.binaryType = 'blob'

socket.onopen = (event) ->
    console.log 'Connection opened (WebSocket)'

socket.onclose = (event) ->
    console.log 'Connection closed (WebSocket)'
    code = event.code
    reason = event.reason
    wasClean = event.wasClean

socket.onmessage = (event) ->
    if event.data instanceof Blob
        reader = new FileReader()
        reader.onload = ->
            console.log reader.result
        reader.readAsText event.data

Alternatively, in ES2015:

// Create socket
socket = new WebSocket("wss://example.org/ws");
socket.binaryType = "blob";

// Log socket opening and closing
socket.addEventListener("open", event => {
    console.log("Websocket connection opened");
});
socket.addEventListener("close", event => {
    console.log("Websocket connection closed");
});

// Handle the message
socket.addEventListener("message", event => {
    if (event.data instanceof Blob) {
        reader = new FileReader();

        reader.onload = () => {
            console.log("Result: " + reader.result);
        };

        reader.readAsText(event.data);
    } else {
        console.log("Result: " + event.data);
    }
});