How to create a Websocket Client with Chrome Extensions?
Asked Answered
H

1

9

I'm trying to create a WebSocket client on Chrome Extensions/Chrome Packaged Apps, that behaves like Simple WebSocket Client from hakobera, or Dark Websocket Terminal from toni.ruottu on Chrome Web Store.

I've been trying to add below code into my Chrome Extensions, but cannot even get any connection working. (my pywebsocket extension on appache runs on localhost)

var ws;
if ("WebSocket" in window) {
  ws = new WebSocket("ws://localhost");
  ws.onopen = function() {
    ws.send("hello");
  };
}

Should I put something special in manifest file? Or should I use other methods to establish a connection within Chrome Extensions? Some code examples or sample projects would be really appreciated.

Thanks!

Hesson answered 12/10, 2012 at 1:48 Comment(3)
did you miss the port number?Mojave
I also tried ws://localhost:80, but the problem is "Websocket" in window does not even evaluate to true. If I insert the code into a single html file as script, then it connects to my localhost properly. But cannot get it to work in Chrome Extensions.Hesson
Could you please provide code for web socket server ? 1. There is no need to add any special thing in manifest file of chrome extension. 2. You current code is working fine with some edits such as port number in ws:// and protocol in web socket object instantiation line.Brancusi
R
-1

Ensure:

  • you specified the https://localhost permission in manifest.json
  • you open the WebSocket from the background page instead of a content script

You can find an example of fully-functioning extension that uses WebSocket.

Rompish answered 10/4, 2021 at 6:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.