Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

322
Vistas
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!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda