ServiceWorker中fetch报错:only-if-cached仅能与same-origin模式同用,求解决方案
Hey there, let's sort out this Service Worker fetch error quickly!
What's Causing the Error?
This error pops up because of a browser security restriction: the only-if-cached cache strategy can only be used alongside the same-origin request mode. When your Service Worker intercepts a request that has cache: 'only-if-cached' set but isn't a same-origin request, calling fetch(event.request) directly violates this rule, triggering the error.
How to Fix It
Here are two practical solutions depending on your needs:
1. Skip Problematic Requests (Let the Browser Handle Them)
If you don't need to customize handling for these specific requests, just skip them and let the browser's default behavior take over:
self.addEventListener('fetch', function(event) { console.log('[Service Worker] Fetching something ...', event); // Check for the conflicting cache/mode combination if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') { // Exit early to let the browser handle this request natively return; } event.respondWith(fetch(event.request)); });
2. Adjust Request Options (With Error Handling)
If you do need to process the request, modify its options to comply with the browser's rules, and add error handling in case the request fails (since cross-origin requests forced to same-origin mode will almost certainly fail):
self.addEventListener('fetch', function(event) { console.log('[Service Worker] Fetching something ...', event); let fetchConfig = {}; // Fix the cache/mode conflict if present if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') { fetchConfig = { mode: 'same-origin', cache: 'only-if-cached' }; } event.respondWith( fetch(event.request, fetchConfig) .catch(err => { console.error('[Service Worker] Fetch failed:', err); // Return a fallback response (customize this to fit your app) return new Response('Resource unavailable', { status: 503 }); }) ); });
Why This Works
The only-if-cached strategy is designed exclusively for retrieving same-origin resources from the browser's HTTP cache—cross-origin use is blocked to prevent potential security risks. By either skipping these requests or adjusting their mode to match the cache strategy, you're aligning with the browser's constraints.
内容的提问来源于stack exchange,提问作者Charles Loh




