Chrome扩展中Service Worker缓存报错:不支持chrome-extension协议
问题分析与解决
错误原因
你遇到的错误是因为Service Worker尝试缓存chrome-extension协议的请求,而Cache API不支持这种非HTTP/HTTPS的协议。问题出在fetch事件监听器中的条件判断——当前代码会对不以http开头的请求执行缓存操作,这就包含了Chrome扩展的请求。
修复方案
需要修正缓存逻辑,只对HTTP/HTTPS协议的请求进行缓存,同时可以额外添加一些过滤条件(比如只处理GET请求、只缓存本站资源)来避免不必要的错误。
修正后的代码
const preLoad = function () { return caches.open("offline").then(function (cache) { // caching index and important routes return cache.addAll(filesToCache); }); }; self.addEventListener("install", function (event) { event.waitUntil(preLoad()); }); const filesToCache = [ '/', '/offline.html' ]; const checkResponse = function (request) { return new Promise(function (fulfill, reject) { fetch(request).then(function (response) { if (response.status !== 404) { fulfill(response); } else { reject(); } }, reject); }); }; const addToCache = function (request) { return caches.open("offline").then(function (cache) { return fetch(request).then(function (response) { return cache.put(request, response); }); }); }; const returnFromCache = function (request) { return caches.open("offline").then(function (cache) { return cache.match(request).then(function (matching) { if (!matching || matching.status === 404) { return cache.match("offline.html"); } else { return matching; } }); }); }; self.addEventListener("fetch", function (event) { // 跳过非GET请求 if (event.request.method !== 'GET') return; const requestUrl = new URL(event.request.url); // 只处理HTTP/HTTPS协议的请求 if (!['http:', 'https:'].includes(requestUrl.protocol)) return; // 可选:只缓存本站资源(替换成你的域名) // if (requestUrl.origin !== self.location.origin) return; event.respondWith(checkResponse(event.request).catch(function () { return returnFromCache(event.request); })); event.waitUntil(addToCache(event.request)); });
关键修改点
- 过滤非GET请求:Cache API仅支持缓存GET请求,因此直接跳过其他方法的请求。
- 验证协议:通过
URL对象检查请求协议,只处理HTTP/HTTPS的请求,避免尝试缓存Chrome扩展或其他非标准协议的资源。 - 可选的域名过滤:如果只需要缓存本站资源,可以添加域名检查,防止缓存外部资源。
内容的提问来源于stack exchange,提问作者Lucky
相关产品推荐
相关产品推荐

