問題:
PWA安裝到手機桌面之后,每次 Flutter Web 打包發(fā)布之后楣嘁,第一次打開不能加載到最新的界面磅轻,關(guān)閉后,下一次打開才能加載最新的马澈。
解決:
將下面代碼添加到 web/index.html 中 <script> 標(biāo)簽里瓢省,后續(xù)通過修改 version 來更新版本 。
const version = 1;
const checkAppUpdate = function() {
caches.open('sugar-cache').then(function(cache) {
// 檢索版本號資源
cache.match('/version').then(function(response) {
if (response) {
response.text().then(function(data) {
var cachedVersion = parseInt(data, 1); // 將緩存的版本號轉(zhuǎn)換為整數(shù)
if (version > 1 && cachedVersion < version) {
// 緩存的版本號較舊痊班,需要更新
window.showToast("There is a new version");
window.location.reload();
// 將最新版本添加到緩存
var versionResponse = new Response(version.toString());
cache.put('/version', versionResponse);
}
});
} else {
// 版本號資源不存在于緩存中勤婚,需要添加到緩存
var versionResponse = new Response(version.toString());
cache.put('/version', versionResponse);
}
});
});
}
const swRegister = function() {
const SW = navigator.serviceWorker
if ('serviceWorker' in navigator) {
// "/serviceworker.js" './service-worker.js' flutter_service_worker.js
SW.register('./flutter_service_worker.js').then((registration) => {
// 捕獲到registration.installing觸發(fā)
registration.onupdatefound = function(){
const installingWorker = registration.installing;
installingWorker.onstatechange = function(){
// 發(fā)布時每次更新了新的內(nèi)容,用戶首次看到的是舊的內(nèi)容涤伐,要二次刷新的問題
if(installingWorker.state === 'activated'){
if(SW.controller){
checkAppUpdate();
}
}
}
}
},
(err) => {
console.log('ServiceWorker registration failed: ', err)
}
);
}
}
swRegister();
參考:
https://blog.csdn.net/zmx_FZ/article/details/106206890
Service Worker 概覽 :
https://developer.chrome.com/docs/workbox/service-worker-overview?hl=zh-cn