简体   繁体   中英

Set WebSocket Origin header in JavaScript

Im currently trying out Webpack and want to send a WebSocket request to a certain url, however in order to properly verify I need to set my Origin header for my socket. This is easly done in Node.js with the WS lib as the WebSocket constructor takes options. However if I try to use the WS lib and pack it with Webpack I get the error:

main.js:formatted:1542 Uncaught Error: ws does not work in the browser. Browser clients must use the native WebSocket object

I understand what the issue is, however I do not see how I can accomplish my task as the standart WebSocket library does not allow to edit its request headers.

Any help would be appreciated.

Code with WS

import msgpack from 'msgpack-lite';
import WebSocket from 'ws';

function component() {

  var connection = new WebSocket('wss:social.krunker.io/ws',{
      headers: {
          origin: "https://krunker.io" // add origin header
      }
  });
  connection.binaryType = "arraybuffer";
  connection.onmessage = function(event) {
    let data = msgpack.decode(new Uint8Array(event.data)); // decode the binary data with msgpack.decode
    console.log("Incoming ->", data);
  };
  return element;
}

document.body.appendChild(component());

^ Throws me the "ws does not work in the browser" error

Code with standart WebSocket lib

import msgpack from 'msgpack-lite';

function component() {

  var connection = new WebSocket('wss:social.krunker.io/ws');
  connection.binaryType = "arraybuffer";
  connection.onmessage = function(event) {
    let data = msgpack.decode(new Uint8Array(event.data)); // decode the binary data with msgpack.decode
    console.log("Incoming ->", data);
  };
  return element;
}

document.body.appendChild(component());

Connecting works, however the request answer is an error message as my origin is not correct.

I have this example running in Node.js and Electron flawlessly, however I need to be on a different protocol than File:// to be able to call captchas later.

The only solution I see currently is to run my html file on a local server and to edit my host file to point its ip to my desired origin to fool the webbrowser.

I chose to use a different approach to my task. To be able to bypass the Origin restriction I ended up using Express together with Socket.io to build a webpage that communicates with my node server which does all the heavy lifting for the connection, the webpage is used to fetch and solve the captcha while also working as a UI for my Node instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM