Javascript Websocket Subscribe to Channel

senty picture senty · Mar 25, 2018 · Viewed 12.3k times · Source

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?

Answer

Dinesh picture Dinesh · May 17, 2018

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);
}