Can a browser execute "on close" WebSocket event when closing the browser?

Viewed 339

When a browser or tab is closed, I have a small snippet that sends an XHttpRequest to a given endpoint to signal that the WebSocket connection has been dropped abnormally.

wsConnection.onclose = function(event) {
  axios.post('/state', { reason: 'abnormal' });
};

Is there a guarantee that the browser will execute the event on a tab/window close? If not, then how do I detect the "client disconnected forcefully"?

1 Answers

No. You can't even guarantee that your ajax call is executed (for example crash or internet connection dropped).

You should use client.ping() on the server-side to detect if a client has a connection loss. WebSocket-Clients are forced by RFC 6455 to answer to ping-requests by the server.

If the status-code is 1006, the connection was closed abnormal.

Related