Can MSW intercept calls being made by another Service Worker? #342
Replies: 1 comment 5 replies
-
Hi, @mickeypuri. I don't believe that's possible. The // some-worker.js
self.addEventListener('fetch', (event) => {
event.respondWith(
// If this fetch triggers the "fetch" event in the worker,
// it will cause an infinite loop.
fetch(event.request)
)
}) You can, however, combine multiple Service Workers via // some-worker.js
importScripts('/mockServiceWorker.js')
self.addEventListener('fetch', (event) => {
event.respondWith(
// If this fetch triggers the "fetch" event in the worker,
// it will cause an infinite loop.
fetch(event.request)
)
}) By sharing the scope, one service worker can spy on the MSW doesn't do that because it's an extremely specific behavior. It sounds like the setup you have to establish on your end. If you are okay with that, this is what I suggest: // your-worker.js
// Import MSW first so it adds the "fetch" listener first.
importScripts('/mockServiceWorker.js')
self.addEventListener('message', (event) => {
// In the handler for the client messages that trigger
// requests, forward those requests onto the global scope.
if (event.data.type === 'REQUEST') {
const request = new Request(event.data.requestInfo)
// This will trigger all "fetch" event listeners
// in your Service Worker and in MSW's service worker as well.
self.dispatchEvent(new FetchEvent('fetch', {
request,
}))
}
}) This should be a good point to get you started. |
Beta Was this translation helpful? Give feedback.
-
In our application, for efficiency, all network calls are made via a Service Worker. So the application sends a message to the Service Worker which makes the network call and returns the response to the application.
Given this scenario, is it still possible to use the MSW library and how, or would we be better to roll our own solution for this use case?
Beta Was this translation helpful? Give feedback.
All reactions