Search code examples
websocket

After calling socket.close() , "websocket closed" message not getting printed from websocket close addEventListner , html, vanilla javascript


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?


Solution

  • You need to use the beforeunload event. This will trigger before the page unloads. You don't have many options:

    1. Try to close the connection just before the page unloads without prompting the user. 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();
    });
    
    1. Prompt the user to make sure they are sure they want to navigate away.
    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)