Keeping a socket connection active in app extension in a Safari Web Extension

I’m currently porting a Chrome Extension to Safari and integrating it with native messaging in a Safari Web Extension. As part of this, I’m building a proxy to forward messages between the web extension and a socket in another application, both ways. Additionally, the socket occasionally broadcasts messages that also need to be sent to the web extension.

The issue I’m facing is that the app extension terminates whenever I call context.completeRequest(returningItems: nil), which prevents me from listening for incoming messages from the socket (I'm using the Network Framework). To work around this, I’ve tried not calling context.completeRequest(returningItems: nil), which keeps the app extension running. However, I’m unsure if this is the right approach—currently, I’m simply ignoring the response and relying entirely on SFSafariApplication.dispatchMessage.

According to the documentation, the app extension lifecycle ends when the system terminates it, but I need to keep the socket listener active.

Has anyone encountered a similar issue, or does anyone have suggestions for maintaining the socket connection while adhering to the app extension lifecycle?

Any insights would be greatly appreciated!

Answered by Engineer in 823296022

Safari Extensions and most app extensions in general are designed to be short lived.

There is not a way to keep it alive for real time messaging.

You can use a background script on MacOS to listen for updates, but on iOS this is not possible.

Safari Extensions and most app extensions in general are designed to be short lived.

There is not a way to keep it alive for real time messaging.

You can use a background script on MacOS to listen for updates, but on iOS this is not possible.

Thank you for your quick response!

I'm developing this exclusively for macOS.

Just to clarify—does this mean the background script in the web extension will need to send requests to the app extension at regular intervals to check for messages from the socket? This doesn’t sound ideal, but if that’s the only way... ;)

Keeping a socket connection active in app extension in a Safari Web Extension
 
 
Q