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

166
Views
Javascript Websockets Disconnect on Page Unload

I am working to build an online game using python flask and web technologies that uses web sockets to allow the game to run live. One page of the game is a lobby, on which all the current players are displayed. If a user disconnects from the game, they should, of course be removed from the lobby list.

I figured that in order for the user to disappear from the list promptly, the client's browser will need to manually send the disconnect executing socket.disconnect() or by sending another custom event when the page unloads.

Unfortunately I just can't seem to get this to run using the onunload event - it runs when the page loads, not when you leave the page. I also can't find a way to use the onbeforeunload event as I'm already using this to display a confirmation pop-up.

Any suggestions on this would be greatly appreciated! Thanks in advance!

My client side code:

    window.addEventListener("beforeunload", function(event) {if (!intentionalForward) {event.preventDefault(); event.returnValue = " "}});
    window.addEventListener("unload", function () { socket.emit("test","testing unload event"); });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

What happens is, you call socket.emit and assign result of that call as event listener to unload event. You should use a closure function like this:

window.addEventListener("unload", function() { socket.emit("test","testing unload event"); });
about 4 years ago · Juan Pablo Isaza Report

0

I managed to get this working properly by forcing the client to connect using the websocket transport (by adding the {transports: ["websocket"]} flag to my io.connect function). This means that the disconnect event now works on the server.

N.B. I was required to install and use gunicorn from this point as the flask development server does not support websockets.

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!