Websockets are subject to the same origin policy. There's nothing you can do to violate the SOP via websockets that you wouldn't be able to do with regular HTTP or XHR.
index.html:
<html>
<head></head>
<body>
<div id="message"></div>
<script>
let ws = new WebSocket("ws://localhost:5000/");
ws.onopen = () => ws.send("hello server!");
ws.onmessage = ev => {
const $message = document.getElementById("message");
$message.textContent = `ws://localhost:5000/ response: ${ev.data}`;
};
</script>
</body>
</html>
server.js: const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on("connection", ws => {
ws.on("message", message => {
console.log(`received: ${message}`);
ws.send("hello client");
});
});
server.listen(5000, () => console.log("ws server listening on localhost:5000"));
Server runs on localhost:5000. Now serve index.html from any other origin and see it talk to the server without any problem.