InvalidStateError on websocket object
The WebSocket.onopen property is an EventHandler that is called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data.
Once you've opened your connection, you can begin transmitting data to the server.
window.onload = function() {
var service = new WebSocket("wss://echo.websocket.org");
service.onmessage = function(event) {
alert("onmessage event: "+event.data);
}
service.onopen = function() {
service.send("test"); //Will work here!
//^^^^^^^^^^^^^^^^^
service.send("hello!");
}
service.onclose = function() {
alert("closed");
}
service.onerror = function() {
alert("error");
}
//Can't close while a connection is still being established.
//service.close();
}
If you use Websocket().send() outside your service.onopen(), you can still check the readyStatebefore sending message, like this:
websocket.sendmessage = async function(msg) {
while (this.readyState === 0) {
await sleep(200);
}
this.send(msg);
};