5

So, I'm using ws package for my backend, and this is my server that I copied from getting started page:

import { WebSocketServer } from 'ws' const wss = new WebSocketServer({ port: 8080 }) wss.on('connection', function connection(ws) { ws.on('message', function message(data) { console.log('received: %s', data) }) ws.send('something') }) 

Now, in my browser console I run this :

const socket = new WebSocket("ws://localhost:8080") 

I get an error:

Content Security Policy: The page’s settings blocked the loading of a resource at ws://localhost:8080/ (“connect-src”).

I've done some googling, and it seems like the connection should be secure in order it to work? However, MDN and other sources do not mention it anywhere. Am I doing something wrong? I'd appreciate any help.

2
  • You don't need a secure context for WebSockets. Something else may be blocking ws://localhost:8080. Perhaps CORS? Commented Nov 26, 2021 at 13:10
  • @IvanRubinson thanks, I'll look into it. Commented Nov 26, 2021 at 13:26

2 Answers 2

3

This error is due to Content Security Policy (mdn) as it's written over there. And if you were running a local server and tried this in that, it would've been worked.

in my browser console I run this

So, here is a problem. The new tab, or wherever you've run this, might have blocked this request to protect against XSS or something like that. The easiest thing to make this work is to add a meta tag <meta http-equiv="Content-Security-Policy" content="connect-src 'ws://localhost:8080';"> to the HTML page or run a local server.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but it's not working for some reason for me. Maybe there are other issues that I have to investigate.
Did you try to run a local server?
Running it from a local server helped me to solve this problem. Establishing websocket connection from a console causes CSP issues. I didn't need the meta tag you mentioned though.
2

Creating a websocket connection in a browser console was failing for some reason, however, after I created a simple html page with a script it worked without any problems:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body></body> <script> const socket = new WebSocket('ws://localhost:8080') console.log(socket) </script> </html> 

I hope it saves some time for other people.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.