'Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable when accessing available var

I'm writing a client that communicates 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?



Solution 1:[1]

This 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("add", (ev) => {
  socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milkias Yeheyis