我正在尝试将一个简单的网页转换为 PWA,以防它使用的网站出现故障。
我想我已经完成了大部分工作。该页面可安装在我的手机上,并通过了所有 Chrome 灯塔测试。但我收到以下警告,
Web app manifest meets the installability requirements
Warnings: Page does not work offline. The page will not be regarded as installable after Chrome 93, stable release August 2021.
我还在控制台中收到以下警告和错误,
The FetchEvent for "https://dannyj1984.github.io/index.html" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) @ serviceWorker.js:30
serviceWorker.js:1 Uncaught (in promise) TypeError: Failed to fetch
然后会出现一条警告,指出该网站无法安装,因为无法离线工作。我读过 chrome 开发文章,其中提到从 8 月 21 日的 chrome 版本开始,无法离线工作的应用程序将无法安装。但我对我的提取的哪一部分造成了问题感到困惑。我的 Service Worker 中的代码是,
const TGAbxApp = "TG-ABX-App-v1"
const assets = [
//paths to files to add
]
self.addEventListener("install", installEvent => {
installEvent.waitUntil(
caches.open(TGAbxApp).then(cache => {
cache.addAll(assets)
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
上面的代码是我从 Google 获取的 Service Worker 的获取部分,据我了解,它首先检查安装时存储的缓存中是否有数据,如果没有,它将从网络请求数据。
最佳答案
https://developer.chrome.com/blog/improved-pwa-offline-detection/
从 Chrome 89 March 2021 开始,如果此检查未通过,它会发出警告: 安装的 Service Worker 获取事件在模拟离线模式下返回 HTTP 200 状态代码(表示获取成功)。
因此,在您的情况下,当 fetch(event.request) 失败时,服务工作线程应返回缓存的“index.html”。
关于progressive-web-apps - PWA 无法正常离线工作。未捕获( promise )TypeError : Failed to fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66649964/