Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!