I am trying to close my websocket connection when I switch to another page within the application, below is the code inside the script tag
below is the code written inside script tag
const type = "onpagehide" in self ? "pagehide" : "unload";
window.addEventListener(type, (event) => {
if (event.persisted === false) {
socket.addEventListener("close", (event) => {
console.log("Websocket closed");
});
// client is gone
socket.close();
}
});
It shows in a closing state with socket.readyState as 2 , but doesn't get closed. What can be the solution on above issue?
You need to use the beforeunload event. This will trigger before the page unloads. You don't have many options:
beforeunload
cannot be made to wait for your function to finish without prompting the user. So it is not guaranteed to close.socket.addEventListener("close", (event) => {
console.log("Websocket closed");
});
addEventListener("beforeunload", (event) => {
socket.close();
});
socket.addEventListener("close", (event) => {
console.log("Websocket closed");
});
window.addEventListener('beforeunload', (event) => {
event.returnValue = 'Are you sure you want to leave this page?'
socket.close();
});
This provides time for the socket to close. I don't think there's any other options. It's also worth limiting the socket timeout on the server.
(Also the message may not show in all browsers, e.g Chrome shows their default message)