'Getting socket.io to reconnect when re-entering the page with the back button

everyone -

I have a feature I'm trying to add to a Node.js application that uses socket.io (4.x, if it matters). I am creating a game where I would like the user to reconnect to their existing game if they disconnect and then reconnect.

Reconnecting works fine if you refresh the page. However, if, for example, I navigate somewhere else and then hit the back button, the reconnection does not happen. For example, just to test it out, I have:

/*Server side:*/
socket.on('connection',(socket)=> {
  const pinger = setInterval(() => {
    io.to(socket.id).emit('ping', null);
  }, 1000);
  ...etc...
}

/*Client side:*/
const socket = io();
socket.on('ping',(data)=> {
  console.log('ping');
});

What I see is a "ping" event every second (as expected). I go to a different page, and then hit the back button. The page re-renders, but the "ping" event does not come back. After around 30 seconds, the connection re-establishes, but I would like it to try to re-establish immediately.

Is there an easy way to force the game to re-establish the connection to the server sooner?

Thanks in advance!



Solution 1:[1]

I've encountered the exact same problem and my solution was to add a listener to the pageshow event (with the 'e' argument in the callback), then check the value of e.persisted, and if e.persisted equals true (means that current page load is not an initial load) I then call window.location.reload() to reload the page.

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 Tyler2P