Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda