[英]How to reload PWA cache? - Angular 11 PWA, Chrome Android
過去幾天我一直在努力在我的 Angular 11 應用程序中加載新的 PWA 版本。 開始拔頭發了!
這對我來說沒有發生:
“每次用戶打開或刷新應用程序時,Angular 服務工作者都會通過查找 ngsw.json 清單的更新來檢查應用程序的更新。如果找到更新,則會自動下載並緩存它,並將提供給下次加載應用程序時。"``` Angular - 生產中的服務人員
我正在使用 Angular 服務SwUpdate.checkForUpdate()
效果很好,並在新版本可用時檢測並提示用戶重新加載。 該應用程序已重新加載並在新版本上,非常完美。
但是,如果我關閉手機上的應用程序,然后重新打開,它總是會回到安裝 PWA 時的第一個版本:(
我試過SwUpdate.activateUpdate()
window.location.reload()
,更改版本號,自定義服務工作者......等等。
唯一可行的是清除我在 Chrome 中的瀏覽數據,然后重新安裝 PWA:(
我無法做任何事情來導致 PWA 緩存使用新版本進行更新。 它正在獲取新版本,但緩存未更新。
有人可以在這里指出我正確的方向嗎? 我錯過了什么?
Android 10,鉻 89.0.4389.105
主要問題是 index.html 的最長期限為 30 天。 在我看來,Android 上的 Chrome 在訪問pwa緩存之前首先從標准瀏覽器緩存加載。
這在 Chrome 桌面上沒有發生,我測試的只是 Android。
我通過以下方式解決了這個問題:
根據您的情況,可能不需要額外的步驟:
ngsw.config.json
以強制從網絡加載。 自定義服務工作者,在app.module.ts
ServiceWorkerModule.register('./offline-service-worker.js', { enabled: environment.production }),
offline-service-worker.js
文件:
const CACHE_NAME = 'offline';
const OFFLINE_URL = '/assets/offline-page.html';
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
await cache.add(new Request(OFFLINE_URL, {cache: 'reload'}));
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
if ('navigationPreload' in self.registration) {
await self.registration.navigationPreload.enable();
}
})());
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
// First, try to use the navigation preload response if it's supported.
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(OFFLINE_URL);
return cachedResponse;
}
})());
}
});
importScripts('./ngsw-worker.js');
整個 PWA 是一件棘手的事情。 但是當它起作用時很棒!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.