Search code examples
websocketmobile-safarichrome-for-androidmobile-chromefirefox-android

What happens with WebSocket connections when a phone's screen locks?


When a phone browser has an open connection, and the user locks the screen, then at a certain point they will no longer have a WebSocket connection.

What events are fired when this happens? Is the WebSocket.onerror or WebSocket.onclose handler called, and if so, does this happen when the screen locks/the app is suspended, or when the app comes back up again?

(And bonus question: is this standardised, or do browsers behave differently, and if so, how?)


Solution

  • I've done some testing myself, and the answer seems to be: no events are fired. Although the connection does drop, no error or close events are fired, not even when the browser comes back up. Therefore, the main way to deal with this appears to be to periodically check the connection status, and reconnect if need be - with exponential back-off in case the connection drops server-side. (Or to have a library do this for you, though I haven't found a properly maintained client-side browser-based WebSocket library that does this yet.)

    This seems corroborated by the author of this article:

    Mobile devices introduce a new category of connection issues; if a mobile device is locked, goes to sleep or the application is moved to the background, an active WebSocket connection may become unresponsive and not close itself properly.