The beforeunload
event should be avoided. From MDN:
Especially on mobile, the beforeunload event is not reliably fired.
Additionally, it should only be used for saving user data, not closing out a websocket connection.
Rather than closing the connection on beforeunload
, I would use the pagehide
or (fallback) unload
event, as the Chrome developer documentation suggests.
const terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
window.addEventListener(terminationEvent, (event) => {
if (event.persisted === false) {
// client is gone
socket.onclose = function () { };
socket.close();
}
});
Besides being recommended by the spec, the advantage of this approach is that you can still have a prompt confirming the user wants to leave (window.addEventListener("beforeunload", () => return "Are you sure?");
) without disconnecting the user if they choose to stay on the page.
As the Chrome docs say (emphasis added):
The document is still visible and the event is still cancelable at this point.
This could result in unintended closing of the websocket connection if the user doesn't actually leave the page.
onclose
event is triggered unexpectedly, or maybe on purpose, as the user navigates/page is reloaded. I've posted a question asking what the expected behaviour should be, which browser has it right and how we implement auto-reconnect. – Volans