Is it possible to keep a html 5 web pages WebSocket connection open in Mobile-Safari once the screen is locked?
I want to send my users continuous updates throughout the day and it seems silly that their screens should always have to be unlocked to receive those notifications.
Are there any other options?
There is an experimental feature named NSURLSession WebSocket in Safari. This feature is by default enabled on iOS 15 and macOS Monterey. If we disable this feature, WebSocket seems to work fine.
But for this post, I would like to have a general discussion about how to keep your websocket session alive. The WebSocket protocol spec is specified at RFC6455 The basic idea is to enable a bi-directional communcation between client and server, without the need to oepning multiple http connections (e.g., long polling).
In iOS 14 and earlier it was working fine. But in iOS 15 and macOS Monterey, WebSocket breaks when we try to send the first message. There is an experimental feature named NSURLSession WebSocket in Safari. This feature is by default enabled on iOS 15 and macOS Monterey.
After the Websocket connection has been established, a Session is created. @OnOpen annotated method will be invoked indicating that the websocket is “opened”. When there is a message coming, the method annocated with @OnMessage will be called.
I don't think it's possible to keep the connection open while the browser is in the background, or when the screen is locked, the reason being that the app is essentially frozen in memory. Here's a quote from a similar question:
the reason you cant keep a network socket open, is that without your app jumping to the foreground when it receives a connection, it cannot respond to network traffic(because if it is not in the foreground its memory content is frozen).
However, I did find this page on Push Notifications for Websites that shows you 'how to sign up your users to receive notifications even when your site is not running in Safari'.
There are some other options: if you want to send continuous updates, you could write an app and either follow the instructions on Apple's site to keep a socket open permanently, or you could configure the app to implement Push Notifications.
I'm sorry I couldn't find a quick fix, but I hope at least one of these options works for you!
I have found a hacky way to keep WebSocket alive in Mobile Safari.
Basically it's the same solution as for this question.
Create an infinity looping audio file to keep Javascript running:
<audio loop src="http://www.sousound.com/music/healing/healing_01.mp3"></audio>
Note: some user interaction is required to initiate the audio file.
It would be nice if a WebSocket kept the browser alive in the same manner as an audio or video file.
PS this also works on Android.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With