14

I am trying to subscribe to channel using native WebSocket in vanilla javascript (without using any library) [as I have just read it's possible but I am not sure - please correct me if I'm wrong].

I am trying to get the latest price of bitcoin

let ws = new WebSocket('wss://ws-feed.gdax.com');

var params = {
   "type": "subscribe",
   "channels": [{"name": "ticker", "product_ids": ["BTC-USD"]}]
}

ws.onmessage = function(msg) {
    console.log(msg);
}

I am trying to connect to this channel, however I couldn't manage to do it. I am not getting any outputs in the console.

How do I give the parameters into the channel and start listening to it?

senty
  • 12,385
  • 28
  • 130
  • 260

1 Answers1

23

Below is an example on how to subscribe to 'ArticlesChannel' using vanilla html5 websockets.

let ws = new WebSocket('ws://localhost:4000/cable');

ws.onopen = function(){
  //Subscribe to the channel
  ws.send(JSON.stringify({"command": "subscribe","identifier":"{\"channel\":\"ArticlesChannel\"}"}))
}    

ws.onmessage = function(msg) {
    console.log(JSON.parse(msg.data).message);
}
Dinesh
  • 499
  • 5
  • 6
  • 3
    is this natively supported or does this then also need a server side implementation? – Flion Mar 12 '21 at 05:50
  • How to send extra parameters in the above syntax? – Sanjay Prajapati Jun 04 '21 at 08:06
  • @SanjayPrajapati Let's declare the message first, then stringify: ws.onopen = function(){ const msg = { command: "subscribe", identifier: { channel: "ArticlesChannel", } } //Subscribe to the channel ws.send(JSON.stringify(msg)) } – Cong Dec 09 '22 at 06:41
  • @Flion All WebSockets require a client & server. I used to use socket.io but there is a lot of bloat with this library. I now use RxJS websocket for the client and https://github.com/Sawtaytoes/Redux-Observable-Backend/tree/2d561c327421328d64f42dc95c2e24dde5d81bea/packages/websocket for the server implementation. It includes all the wonderful features that socket.io offers, but RxJS allows connections to be cancelled. – Charles Robertson Aug 05 '23 at 14:40