You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次加载/强制刷新远程图片正常,普通刷新经Service Worker触发跨域错误求助

Fixing CORS Error with Service Workers on Normal Page Refresh

Hey there, let’s break down why this is happening and fix it step by step!

Why This Happens

When you do a first load or hard refresh (CTRL + SHIFT + R), the Service Worker isn’t active yet—your browser fetches images directly from the server, which works fine. But on a normal refresh (CTRL + R), the Service Worker takes over all requests, including images. Two common issues trigger the CORS error here:

  1. Your server is returning an invalid Access-Control-Allow-Origin header value ('SAMEORIGIN' is not a valid value for this header).
  2. Your Service Worker’s fetch event logic isn’t handling cross-origin (or same-origin) requests correctly.

Step 1: Fix the Server’s CORS Configuration

First, let’s fix the root issue with the invalid header:

  • If images are hosted on the same domain: Remove the Access-Control-Allow-Origin header entirely. Same-origin requests don’t need CORS validation, so this header is unnecessary here.
  • If images are cross-domain: Update the header to use a valid value:
    • Allow a specific domain: Access-Control-Allow-Origin: https://your-frontend-domain.com
    • Allow all domains (not recommended for production): Access-Control-Allow-Origin: *
      Note: SAMEORIGIN is not a valid value for this header—this is likely a misconfiguration on your server (e.g., copying a setting meant for another header like X-Frame-Options).

Step 2: Adjust Service Worker’s Fetch Logic

Next, make sure your Service Worker handles image requests properly. Here’s a revised fetch handler that accounts for same-origin vs cross-origin images:

self.addEventListener('fetch', (event) => {
  const request = event.request;

  // Target only image requests
  if (request.destination === 'image') {
    const isSameOrigin = new URL(request.url).origin === self.location.origin;
    
    // Set correct fetch options based on origin
    const fetchOptions = {
      mode: isSameOrigin ? 'same-origin' : 'cors',
      credentials: isSameOrigin ? 'include' : 'omit' // Adjust credentials as needed
    };

    event.respondWith(
      fetch(request, fetchOptions)
        .then((response) => {
          // Optional: Cache successful responses for future use
          if (response.ok) {
            caches.open('image-cache-v1').then((cache) => {
              cache.put(request, response.clone());
            });
          }
          return response;
        })
        .catch((err) => {
          // Fallback to cached image or placeholder if fetch fails
          console.error('Image fetch failed:', err);
          return caches.match(request) || new Response('<img src="/fallback-image.png" alt="Fallback image">', {
            headers: { 'Content-Type': 'text/html' }
          });
        })
    );
  }
});

Key fixes here:

  • We explicitly set the mode based on whether the image is same-origin or cross-origin, ensuring the browser uses the correct CORS handling.
  • We only cache valid responses to avoid storing broken or error-filled cache entries.

Step 3: Verify the Fix

  1. Deploy your updated server configuration and Service Worker code.
  2. Do a hard refresh (CTRL + SHIFT + R) to activate the new Service Worker and clear any old cached responses.
  3. Do a normal refresh (CTRL + R) and check the browser’s console: the CORS error should be gone, and images should load correctly.
  4. Double-check the Network tab in DevTools to confirm the Access-Control-Allow-Origin header is valid (or removed for same-origin images).

内容的提问来源于stack exchange,提问作者Gausool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:58:41