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

2

5

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?

Lancers answered 25/2, 2022 at 21:12 Comment(0)
P
10

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("open", (ev) => {
  socket.send(JSON.stringify({"type": "getplayerinfo", "token": token}));
  });
Pelton answered 22/4, 2022 at 15:40 Comment(0)
O
0

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.

Outgo answered 10/9 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.