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

大学项目PWA开发遇Uncaught报错及Chrome审计失败求助

Troubleshooting Your PWA Service Worker Errors & Audit Failures

Hey there, let's break down what's going on with your PWA and fix those issues step by step—those errors and audit failures are all linked to your service worker not functioning correctly, so we'll start there.

First: Debug the Uncaught (in promise) TypeError: Request failed Error

This error almost always happens when your service worker hits a snag during installation or fetching resources. Here's how to track it down:

  • Double-check your service worker registration code
    Make sure the code in your main JS file (like app.js or inline in your HTML) is correctly pointing to your serviceworker.js file, and handles errors properly. Example of working registration code:

    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/serviceworker.js')
          .then(reg => console.log('Service Worker registered successfully:', reg))
          .catch(err => console.error('Service Worker registration failed:', err));
      });
    }
    

    Pay close attention to the path: if serviceworker.js isn't in your project root, adjust the path (e.g., /js/serviceworker.js if it's in a js folder).

  • Audit your service worker's cache setup
    The error often pops up when cache.addAll() tries to fetch a resource that doesn't exist or has a wrong path. Open your serviceworker.js and verify the list of assets you're trying to cache:

    const CACHE_NAME = 'my-pwa-cache-v1';
    const ASSETS_TO_CACHE = [
      '/',
      '/index.html',
      '/styles.css',
      // Double-check every path here—typos or missing files will break installation
    ];
    
    self.addEventListener('install', (event) => {
      event.waitUntil(
        caches.open(CACHE_NAME)
          .then(cache => cache.addAll(ASSETS_TO_CACHE))
          .catch(err => console.error('Cache installation failed:', err))
      );
    });
    

    If any asset in ASSETS_TO_CACHE is missing or misspelled, the entire cache operation fails, throwing that "Request failed" error.

  • Use Chrome DevTools to inspect service worker status
    Open DevTools → Application → Service Workers. Here you can see if your SW is activated, waiting, or errored. If it's errored, click "Inspect" to open the SW's dedicated console—this will show you the exact line where the failure happened, making it easy to fix.

Next: Fix the Lighthouse Audit Failures

All three failed audit checks are direct consequences of your service worker not working. Once you resolve the above error, these should start to pass, but here's how to make sure:

  • "No service worker detected"
    This will automatically pass once your SW is successfully registered and activated. Ensure there are no syntax errors in serviceworker.js (like missing brackets or typos) and that your registration code runs without issues.

  • "No 200 when offline"
    You need a fetch event handler in your service worker to serve cached assets when offline. Add this to serviceworker.js:

    self.addEventListener('fetch', (event) => {
      event.respondWith(
        caches.match(event.request)
          .then(cachedResponse => {
            // Serve cached asset if available, otherwise fetch from network
            return cachedResponse || fetch(event.request);
          })
          .catch(() => {
            // Fallback to an offline page if both cache and network fail
            return caches.match('/offline.html');
          })
      );
    });
    

    Make sure you've added offline.html (or your preferred fallback) to your ASSETS_TO_CACHE list.

  • "User not prompted to install web app"
    This requires a few boxes to be checked:

    • Your service worker is active and working
    • You have a valid manifest.json with these required fields:
      {
        "name": "Your PWA Name",
        "short_name": "PWA",
        "start_url": "/",
        "display": "standalone",
        "icons": [
          {
            "src": "/icon-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
          }
        ]
      }
      
    • You've linked the manifest in your HTML: <link rel="manifest" href="/manifest.json">
    • The user has interacted with your site (e.g., clicked a button, scrolled)—Chrome won't show the install prompt immediately on load.

Quick Pro Tips

  • When testing locally, use Chrome's Incognito mode to avoid conflicts with cached old service workers.
  • Every time you update your service worker or cached assets, increment your CACHE_NAME (e.g., my-pwa-cache-v2) to trigger a fresh installation.
  • For local development, HTTPS isn't required (localhost is exempt), but make sure to use HTTPS when deploying to production.

内容的提问来源于stack exchange,提问作者K. Brennan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:01:18