问题描述
我的 Service Worker 有问题。
我目前正在使用 offline.html 站点实现离线功能,以便在网络出现故障时显示。我已按照此处所述实现了导航预加载:https://developers.google.com/web/updates/2017/02/navigation-preload#activating_navigation_preload
这是我的安装 EventListener 被跳过等待()并初始化新缓存
const version = 'v.1.2.3'
const CACHE_NAME = '::static-cache'
const urlsToCache = ['index~offline.html','favicon-512.png']
self.addEventListener('install',function(event) {
self.skipwaiting()
event.waitUntil(
caches
.open(version + CACHE_NAME)
.then(function(cache) {
return cache.addAll(urlsToCache)
})
.then(function() {
console.log('WORKER: install completed')
})
)
})
这是我的 激活 EventListener 功能检测导航预加载并启用它。之后我检查旧缓存并删除它们
self.addEventListener('activate',event => {
console.log('WORKER: activated')
event.waitUntil(
(async function() {
// Feature-detect
if (self.registration.navigationPreload) {
// Enable navigation preloads!
console.log('WORKER: Enable navigation preloads')
await self.registration.navigationPreload.enable()
}
})().then(
caches.keys().then(function(cacheNames) {
cacheNames.forEach(function(cacheName) {
if (cacheName !== version + CACHE_NAME) {
caches.delete(cacheName)
console.log(cacheName + ' CACHE deleted')
}
})
})
)
)
})
这是我的获取事件监听器
self.addEventListener('fetch',event => {
const { request } = event
// Always bypass for range requests,due to browser bugs
if (request.headers.has('range')) return
event.respondWith(
(async function() {
// Try to get from the cache:
const cachedResponse = await caches.match(request)
if (cachedResponse) return cachedResponse
try {
const response = await event.preloadResponse
if (response) return response
// Otherwise,get from the network
return await fetch(request)
} catch (err) {
// If this was a navigation,show the offline page:
if (request.mode === 'navigate') {
console.log('Err: ',err)
console.log('Request: ',request)
return caches.match('index~offline.html')
}
// Otherwise throw
throw err
}
})()
)
})
现在我的问题: 在 localhost 上的本地机器上,一切正常。如果网络处于离线状态,index~offline.html 页面将交付给用户。如果我部署到我的测试服务器,一切都按预期运行,除了 Chrome 在正常浏览(非离线模式)时出现奇怪的错误消息:
The service worker navigation preload request Failed with network error: net::ERR_INTERNET_disCONNECTED.
DOMException: The service worker navigation preload request Failed with a network error.
这很奇怪,因为无论加载哪个站点,都会以某种方式请求 index.html。
附加信息这发生在 Chrome 89 中,在 chrome 88 中一切似乎都很好(我检查了浏览器堆栈)。我刚刚看到 Chrome 89 中的 pwa 离线检测发生了变化...... https://developer.chrome.com/blog/improved-pwa-offline-detection/
有人知道可能是什么问题吗?
更新 我在这里重建问题,以便每个人都可以查看:https://dreamy-leavitt-bd4f0e.netlify.app/
解决方法
此错误直接由您链接到的改进的 pwa 离线检测引起: https://developer.chrome.com/blog/improved-pwa-offline-detection/
浏览器伪造离线上下文并尝试请求清单的 start_url,例如在您的 https://dreamy-leavitt-bd4f0e.netlify.app/site.webmanifest
中指定的 index.html这是为了确保您的 Service Worker 在这种情况下实际上返回了有效的 200 响应,即您的 index~offline.html 页面的有效缓存响应。
您具体询问的错误来自 await event.preloadResponse
部分,显然无法抑制。
await fetch
调用会产生类似的错误,但可以抑制这种错误,只是不要在 console.log
部分中 catch
。
希望将来在进行离线 pwa 检测时,chrome 不会从预加载响应中显示此错误,因为它会造成不必要的混乱。