2

I am connecting to a JSON-RPC server from an HTML5 page, via websockify.

I am basing my code on the canonical websocket echo example. Pseudocode follows:

In the HTML part:

<P id="testview"></P>

In the script part:

el = document.getElementById("testview");
var sock = new WebSocket("ws://localhost:5555", ['binary'] );
sock.onopen = function(evt) { onOpen(evt) };      // sends request
sock.onmessage = function(evt) { el.innerHTML = evt.data; }

Eventually I would like to JSON parse the result but a first step would be to be able to display it unparsed.

However currently the display produced in el by this code is [Object BLOB].

How do I make it display { "method" : "blabla", etc., i.e. the actual content of the received data (which is human-readable ASCII).

The output of console.log(evt.data) is:

Blob {}
  size: 74
  type: ""
  __proto__: Blob
    constructor: Blob() { [native code] }
    size: (...)
    get size: () { [native code] }
    slice: slice() { [native code] }
    type: (...)
    get type: () { [native code] }
    __proto__: Object

If I change the WebSocket to open as ['base64'] instead of binary, and I base64-encode my request, then I get back a base64 string which I am able to work with. However this seems like a waste of bandwidth and encoding compared to just sending and receiving plain ASCII which JSON-RPC is.

NB. Any alternative suggestions as to how to talk to JSON-RPC from HTML5 are welcome too.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    I think the [readAsText](https://msdn.microsoft.com/en-us/library/windows/apps/hh453241.aspx) method might work for converting the Blob object to text. It's an interesting question. – Yogi May 27 '15 at 14:14
  • @Robert `var reader = new FileReader(); reader.onload = function(event) { ...bla... }; reader.readAsText(evt.data);` worked! So that is good progress... but I wonder if there is a way that doesn't use another asynchronous call. I'm a bit surprised that this isn't a more common use-case (consuming a JSON-RPC service from a web page) – M.M May 27 '15 at 14:22

0 Answers0