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

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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