I am new to websockets and have been asked to investigate a problem we’re having with our app. Our app uses xmpp.js, and its behavior when there is no internet connection is different depending on the browser.

For example, when the the internet connection is cut, our app goes into offline mode. However, we’ve noticed that on some pages, Chrome and Safari will never go into offline mode, while Firefox always does in 10 seconds. Additionally, on pages where Chrome and Safari do go into offline mode when there is no internet, the time that they detect disconnection differs. On Safari it seems to be 2 minutes, while on Chrome it takes around 1.5 to 2.5 minutes.

I went through the source code of xmpp.js, and it appears that the package is basically waiting for websocket to tell it that the connection has been closed. So that leads me to think that different browsers have different implementations on when to close the websocket connection. Is this assumption of mine correct?

1 Answer 1


Yes, different web browsers can have different implementations for closing a WebSocket connection. The WebSocket API provides a standardized way for creating and managing WebSocket connections, but the specifics of how the connections are closed can vary depending on the browser.

The WebSocket API provides the close() method for closing a WebSocket connection, which you can call on the WebSocket instance. For example:

const socket = new WebSocket('ws://example.com');

// Close the connection after 5 seconds
setTimeout(() => {
}, 5000);

This will close the WebSocket connection after 5 seconds. However, the exact timing of when the connection is actually closed can depend on the browser and the network conditions.

Browsers may also decide to close a WebSocket connection under certain circumstances, such as when the user navigates away from the page or closes the tab. In these cases, the onclose event will be fired on the WebSocket instance, and you can handle it as needed.

const socket = new WebSocket('ws://example.com');

socket.onclose = (event) => {
  console.log('WebSocket connection closed:', event.code, event.reason);

The event object passed to the onclose event handler contains a code and a reason property, which provide more information about the reason for the connection being closed.

  • Thank you very much for this! It has confirmed what I suspected, and learned much from it. Cheers! Dec 28, 2022 at 3:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.