Is it possible to intercept and cache WebSocket messages in a Service Worker like all the examples do for normal HTTP requests?

I know you can create WebSocket connections from within a Service Worker itself; my question is more whether or not you can use a WebSocket from your app as normal and have the Service Worker intercept / cache WebSocket requests just like it can do for normal HTTP fetch requests?

Here’s an example of intercepting and caching a normal HTTP request from a Service Worker.

self.addEventListener('fetch', function(event) {
  // If a match isn't found in the cache, the response
  // will look like a connection error

How would I setup the Service Worker if all of my requests were via WebSockets?

It’s not possible for a service worker to intercept Web Socket traffic.

The service worker’s fetch event is triggered only for controlled clients’ HTTPS requests, and the message event is triggered only for postMessage() requests from clients.

While there is an HTTP handshake when initiating a Web Socket connection, that handshake does not trigger a fetch handler, and neither does the actual traffic sent once the connection has been established.

I think one should use fetch for the first load of the page, so its data can be cached and returned by the service worker when you’re offline.

So you initiate the websocket connection only if you’re online. No need to cache data then.

And you fallback in saving message in cache in the app side when it fails to send via socket.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to mock uuid with Jest

Similar Posts