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

Chrome中CacheStorage.open()返回undefined问题排查

Troubleshooting CacheStorage.open() Returning undefined in Chrome for Your Service Worker

Hey there, let's break down why caches.open() might be returning undefined in your Chrome setup, and how to fix it. I'll walk through common issues and actionable fixes based on your code snippet.

Possible Causes & Fixes

1. Missing HTTPS Context (or Invalid Scope)

Chrome restricts Service Worker functionality to HTTPS (with the exception of localhost for development). If your site is served over HTTP (not local), the caches API will be unavailable entirely, leading to unexpected undefined returns.

Additionally, double-check your Service Worker's scope:

  • If your SW file is in a subdirectory (e.g., /sw/sw.js), its default scope is limited to that subdirectory. If you need it to control the entire site, register it with the scope option set to /:
    navigator.serviceWorker.register("/sw/sw.js", { scope: "/" });
    
  • For the most reliable behavior, host your Service Worker file at the root of your domain (e.g., /sw.js).

2. Broken Promise Chain in waitUntil()

Looking at your code snippet, the e.waitUntil() relies on a chain of Promises. If you don't properly return the result of caches.open() or subsequent operations, the Promise chain can break, making it seem like caches.open() returns undefined.

Here's a corrected version of your install handler with a complete, properly chained Promise flow:

/**
 * 安装Service Worker时,将所需资源下载到临时缓存
 * @param e 安装事件
 */
function installHandler(e: ExtendableEvent): void {
  "use strict";
  e.waitUntil(
    caches.delete("core-waiting")
      .then(() => {
        // 明确返回caches.open()的Promise
        return caches.open("core-waiting");
      })
      .then((cache) => {
        // 缓存你的目标资源列表
        return cache.addAll([
          "/",
          "/assets/styles.css",
          "/assets/app.js"
          // 添加其他需要预缓存的资源
        ]);
      })
      .catch((err) => {
        // 捕获并记录错误,避免静默失败
        console.error("Service Worker install failed:", err);
        throw err; // 确保waitUntil registers the failure
      })
  );
}

// 绑定安装事件
self.addEventListener("install", installHandler);

The key here is ensuring every step in the chain returns a Promise—this keeps waitUntil() informed of the operation's progress and prevents premature completion that could lead to undefined results.

3. Corrupted or Unreachable Cache Storage

Sometimes old, corrupted caches can interfere with caches.open(). Try manually clearing existing caches in Chrome:

  1. Open DevTools (F12) → Go to the Application tab
  2. Expand Cache Storage in the left sidebar
  3. Right-click any existing caches and select Delete
  4. Reload your page to trigger a fresh Service Worker install

Also, ensure your cache name (core-waiting) uses valid characters—avoid spaces or special symbols that might cause parsing issues.

4. TypeScript Type Definition Mismatch

If you're seeing undefined in your editor (but not at runtime), it might be a TypeScript type issue. Make sure you've installed the correct Service Worker type definitions:

npm install @types/service-worker-api --save-dev

This ensures TypeScript recognizes the caches API correctly and provides accurate type hints.

Debugging Tips

  • In Chrome DevTools, go to Application → Service Workers and check the "Update on reload" box—this forces Chrome to fetch the latest Service Worker on each reload.
  • Keep the Console tab open while testing to catch any uncaught errors that might be breaking the cache flow.
  • After a successful install, check Cache Storage to confirm the core-waiting cache was created and populated with your resources.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:27:44