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

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

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 Relatório

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