Should WebSocket.onclose be triggered by user navigation or refresh?

后端 未结 1 433
暗喜
暗喜 2020-12-14 00:25

Part 1: Expected behaviour?

I\'m seeing some inconsistent browser behaviour between Firefox and Chrome in relation to the onclose handler being called

相关标签:
1条回答
  • 2020-12-14 01:01

    The unexpected behavior is due to the way in which Firefox and Chrome handle the closing of a Websocket. When the page is refreshed, both browsers close the connection, however, Firefox will execute your onclose code, while chrome closes the connection and skips straight to re-loading the new page. So yes, I confirm this strange behavior.
    Even stranger is the fact that, from my observations, calling websocket.close() in chrome will immediately close the connection and call the onclose function, while Firefox waits for a close message back from the server.

    The wasClean property will be true if a close message was received from the server

    If your library is auto-reconnecting without checking the wasClean property then this could cause a problem, as it tries to re-establish the connection as the page refreshes. You should consider not using the library for this and doing it manually, it should'nt be very hard, just call connect in the onclose function with an if statement making sure the onclean property is true. Or to be even more safe set a variable in onbeforeunload that prevents any new connection.

    hope this helps!

    0 讨论(0)
提交回复
热议问题