Reputation: 492
Is there a way to find if a request is XHR or fetch while using Workbox.
const matchCb = ({url, event}) => {
if(event.type === 'xhr')
{
return true;
}
return false;
};
workbox.routing.registerRoute(
matchCb,
workbox.strategies.networkOnly()
);
I have put a check so that the above route is used only for XHR calls. Although network Tab of the browser shows a certain request to be of the type xhr it is coming out to be fetch on debugging the above code . Am i doing something wrong? Is there some other way to check it?
Upvotes: 0
Views: 801
Reputation: 56044
There's no way to determine that from within Workbox or inside of the service worker. (I'm also not sure why you would want to?)
One thing that you can do, however, is add in an extra request header when you make your request, and then check for that header inside of your service worker. If it's really important for you to distinguish between requests that originated via XHR and va fetch()
, you could use the header for that.
Inside your web app:
const request = new Request('/api', {headers: {'X-Source': 'fetch'}});
const response = await fetch(request);
Inside your service worker, using Workbox:
workbox.routing.registerRoute(
// This matchCallback will only be true if the request
// has an X-Source header set to 'fetch':
({event}) => event.request.headers.get('X-Source') === 'fetch',
workbox.strategies.networkOnly()
);
Note that if you're making a cors
request, you may need to delete that X-Source
request header before sending it to the network, since extra request headers can trigger CORS preflight checks.
Upvotes: 1