Web3.js: Can't connect to remote node when using WebSockets with Javascript in v1.0.0-beta.13 (o is not a constructor)

Created on 30 Jul 2017  路  5Comments  路  Source: ChainSafe/web3.js

Can't seem to be able to connect to a remote node via WebSocket. The browser console gives me the following error:
screenshot 103

Remote node is running on Geth 1.6.7 with
geth --light --ws --wsaddr redacted --wsport 8546 --wsorigins "*"

Here is the code in my script.js that is used to connect (as found here).

var web3 = new Web3(Web3.givenProvider || "ws://redacted:8546");

web3.eth.getProtocolVersion()
.then(console.log);

The code runs perfectly when ran via the Parity (1.7) browser, it results in 63 like it should. When ran via the regular browser, it results in the error stated above.

bug help wanted

Most helpful comment

Workround: Add window.WebSocket to dist/web3.js:55082

var WebSocket = window.WebSocket;
this.connection = new WebSocket(url);

geth 1.6.7

geth --dev --rpc  --ws --wsaddr="0.0.0.0" --wsorigins "*"

HTML

 <script src="web3.js"></script>
 <script type="text/javascript">
    var web3 = new Web3("ws://localhost:8546");
  </script>

Error message in Console

Uncaught TypeError: WebSocket is not a constructor
    at new WebsocketProvider (web3.js:55082)
    at RequestManager.setProvider (web3.js:33478)
    at Object.packageInit (web3.js:34210)
    at new Web3 (web3.js:57070)
    at web3test.html:18

This may be related. https://github.com/theturtle32/WebSocket-Node/blob/master/docs/W3CWebSocket.md

All 5 comments

Running Geth on localhost with geth --light --ws and replacing "ws://redacted:8546" with "ws://localhost:8546" results with the same error that is displayed in the browser.

Running a WebSocket connection via Parity doesn't change anything either.

Hm, its really hard to make this work on the browser and node at the same time, because one of them is not supporting WebSockets :)
Will take a look soon.

Workround: Add window.WebSocket to dist/web3.js:55082

var WebSocket = window.WebSocket;
this.connection = new WebSocket(url);

geth 1.6.7

geth --dev --rpc  --ws --wsaddr="0.0.0.0" --wsorigins "*"

HTML

 <script src="web3.js"></script>
 <script type="text/javascript">
    var web3 = new Web3("ws://localhost:8546");
  </script>

Error message in Console

Uncaught TypeError: WebSocket is not a constructor
    at new WebsocketProvider (web3.js:55082)
    at RequestManager.setProvider (web3.js:33478)
    at Object.packageInit (web3.js:34210)
    at new Web3 (web3.js:57070)
    at web3test.html:18

This may be related. https://github.com/theturtle32/WebSocket-Node/blob/master/docs/W3CWebSocket.md

beta.16 should fix that now

Works wonderfully, thanks a bunch!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sundbry picture sundbry  路  3Comments

ragnu picture ragnu  路  3Comments

connectdotz picture connectdotz  路  3Comments

xpepermint picture xpepermint  路  3Comments

zamoore picture zamoore  路  3Comments