You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Workbox v5迁移后离线访问新页面无响应问题求助

Fixing "no-response" Error & Offline Page Handling in Workbox v5

Hey there, let's break down what's going wrong and fix your Service Worker setup step by step.

The Root Causes of Your Issues

Looking at your code and error logs, two main problems are causing the offline page not to load and the no-response error:

  1. Duplicate & Broken HTML Route: You have two separate routes registered for .html files. The second one references articleHandler, which isn't defined anywhere in your code. This invalid handler throws the no-response promise rejection you're seeing.
  2. Missing Fallback for Offline/Uncached HTML: Your NetworkFirst strategy for HTML files will fail silently when offline and the requested page isn't already cached—there's no logic to fall back to your pre-cached offline.html.

Step-by-Step Fix

Here's the corrected Service Worker code with explanations for each change:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.4/workbox-sw.js')

if (workbox) {
  console.log('Yay! Workbox is loaded');

  // Precache critical offline/404 pages (this part was correct)
  workbox.precaching.precacheAndRoute(
    [
      { url: "404.html", revision: "ca66a569ea978f2cca26acf6994d7e49" },
      { url: "offline.html", revision: "112452c5d7bf793db0ab9a37cf30d178" }
    ]
  );

  // Cache non-HTML assets with CacheFirst (30-day expiration)
  workbox.routing.registerRoute(
    /\.(?:png|gif|jpg|svg|css|js|json)$/,
    new workbox.strategies.CacheFirst({
      cacheName: 'nonhtml-cache',
      plugins: [
        new workbox.expiration.ExpirationPlugin({
          maxEntries: 50,
          maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
        })
      ]
    })
  )

  // Updated HTML handling: NetworkFirst with offline/404 fallback
  workbox.routing.registerRoute(
    /\.(?:html)$/,
    async ({ event }) => {
      try {
        // Attempt to fetch from network first, then fall back to cache
        const response = await new workbox.strategies.NetworkFirst({
          cacheName: 'html-cache',
          plugins: [
            new workbox.cacheableResponse.CacheableResponsePlugin({
              statuses: [0, 200, 206],
            }),
            new workbox.expiration.ExpirationPlugin({
              maxEntries: 50,
              maxAgeSeconds: 5 * 60, // 5 minutes
            })
          ]
        }).handle({ event });

        // If the response is a 404, return our pre-cached 404 page
        if (response.status === 404) {
          return workbox.precaching.matchPrecache('404.html');
        }

        return response;
      } catch (error) {
        // If network fails (offline + no cached page), return offline.html
        return workbox.precaching.matchPrecache('offline.html');
      }
    }
  );

} else {
  console.log('Boo! Workbox did not load');
}

Key Changes Explained

  • Removed the Broken Duplicate Route: We got rid of the second .html route that referenced the undefined articleHandler—this eliminates the no-response error.
  • Wrapped NetworkFirst in Try/Catch: This lets us gracefully handle network failures (like when the user is offline and the page isn't cached).
  • Used workbox.precaching.matchPrecache: Instead of caches.match, this method reliably finds files from Workbox's precache storage, avoiding issues with cache naming conventions.
  • Explicit 404 Handling: We check if the network response is a 404 and serve our custom 404 page instead.

Post-Fix Steps

To make sure the changes take effect:

  1. Update Your Service Worker Registration: Ensure your app is registering the updated SW file, and disable HTTP caching for the SW file itself (so browsers fetch the latest version).
  2. Clear Old Caches: In Chrome DevTools > Application > Cache Storage, delete any old caches from your app to avoid conflicts.
  3. Test Properly: Use Chrome DevTools' Offline toggle (under Network tab) to simulate offline mode—don't just rely on disconnecting your internet, as browsers might use local DNS cache.

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

火山引擎 最新活动