0

So I had the following code on Python that created a websocket connection:

channels_dict = {}
channels_dict['Authorization'] = 'true'
for channel in channels: #adds some extra headers with info
    channels_dict["Channel" + str(channel)] = '1'

ws = websocket.WebSocketApp("ws://localhost:8888/ws",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close,
                              header = channels_dict)

And I could easily add extra headers that I could access later in the server upon connection. Is there a way I could do the same in Javascript? I haven't found much information about setting custom headers in websocket creation. I have the following code in JS:

var webSocket;

function openWebsocket() {
  webSocket = new WebSocket("ws://localhost:8888/ws")
}

I've heard of adding query parameters in the url, is that the only way of adding extra headers/information to a websocket connection in javascript?

1 Answer 1

1

Try this:

 const webSocket = new WebSocket ("ws://localhost:8888/ws"  + "?param1=" + param1); // here you can add other params
 webSocket.on("open", function open(e) {
   console.log("*** websocket opened");
 });
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, now I did this: webSocket = new WebSocket("ws://localhost:8888/ws?param1=yooo"). The server I'm connecting to is basically a Tornado Server but I don't think that matters much. In the next comment I'll put the headers I receive and print in the server when it receives the websocket connection attempt.
Host: localhost:8888 Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Origin: chrome-extension://aegbhodkdcknhkiimijaibmipgknpphb Sec-Websocket-Version: 13 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36 Accept-Encoding: gzip, deflate, br Accept-Language: pt-PT,pt;q=0.9,en-US;q=0.8,en;q=0.7 Sec-Websocket-Key: V7K2QUIifuqI37ao0VZCHA== Sec-Websocket-Extensions: permessage-deflate; client_max_window_bits
I don't think these url params are added to the headers, I'm gonna search where can I access them in the server.
Ok, I think I can access them in the server by the uri I receive. But it's gonna be a little more complicated because I have to analyze the uri string to search for the parameters. Before I was just searching them in the headers dictionary which was very easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.