I'm writing a client that municates with a websocket server. Currently, the socket server sends a generated "token" to the client, which then sets it in storage with:
localStorage.setItem('token', json.token);
And redirects to the next page, which on load, runs this code:
token = localStorage.getItem('token')
console.log(token)
socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
When doing console.log(token), I get the token. However, when sending the token through the socket, I get:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
I've been debugging this for 3 days and have wracked my brain. Any tips?
I'm writing a client that municates with a websocket server. Currently, the socket server sends a generated "token" to the client, which then sets it in storage with:
localStorage.setItem('token', json.token);
And redirects to the next page, which on load, runs this code:
token = localStorage.getItem('token')
console.log(token)
socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
When doing console.log(token), I get the token. However, when sending the token through the socket, I get:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
I've been debugging this for 3 days and have wracked my brain. Any tips?
Share Improve this question asked Feb 25, 2022 at 21:12 ZeptosGTZeptosGT 811 gold badge1 silver badge2 bronze badges2 Answers
Reset to default 11This normally happens when you try to send something through a websocket connection before the connection has fully connected to the server. So what you should do is run the code when the server sends a connected signal which you can using the event listener "open". In your case this would be:
const socket = new Websocket(url);
socket.addEventListener("open", (ev) => {
socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
});
For the sake of any new visitors, here's what I do as for a more practical example (since sending message right inside open
event is not always the case):
let ws; //Global var
async function connect_ws()
{
return new Promise( resolve =>
{
ws = new WebSocket("ws://localhost:12345");
ws.addEventListener("open", event => {
console.log("Connected to WS server!");
resolve();
});
ws.addEventListener("message", ( {data} ) => {
console.log("WS server says: ", JSON.parse(data) );
});
});
}
function send_ws(msg)
{
console.log("Sending message:", msg);
ws.send(msg);
}
And then, use it as follow (or perhaps, using .then()
):
await connect_ws();
send_ws( JSON.stringify(obj) );
Note:
The reason why I'm adding eventHandlers
inside connect_ws()
function is, since ws
is a global var, adding eventHandlers
to it in global scope (outside the function) will run before ws
being initialized!
p.s.: I'm not a pro at Node.js, feel free to correct me.