如何解决Service-worker.js 在更新 Service Worker 时保持内存变量
当 Service Worker 更新时,我一直在思考如何在 Service Worker 中传递保持内存变量。所以基本上我的 service worker 会跟踪应用的版本号以更新离线缓存。
有一部分很棘手,我将用户的访问令牌再次保存在服务工作者的内存中,这没有问题。主要问题是当我更新 Service Worker 中的代码(版本号,...)时,浏览器将从 Service Worker 安装“新版本”。 (并重新加载页面)但是新版本的 service worker 没有以前版本的内存变量。
(我省略了缓存更新,因为它很长..)
Service-worker.js :
const LATEST_VERSION = 'v'+'0.1.alpha';
// Global token variable in the service worker
let token = '';
self.addEventListener('activate',function(event) {
//do all the cache thingis...
});
// These listeners will make the service worker immediately available for the page
self.addEventListener('install',function(event) {
console.log('install - triggered')
event.waitUntil(
caches.open('cache').then(function(cache) {
return cache.addAll([
"/img/no-internet.png"
]);
})
);
});
// Exposed "method" for saving the token
self.addEventListener('message',function(event) {
if (event.data && event.data.type === 'SET_TOKEN') {
token = event.data.token;
console.log("[SW] token set!");
}
})
// Helper function to add the auth header if the oubound request matches the whitelists
const addAuthHeader = function (event) {
destURL = new URL(event.request.url);
const modifiedHeaders = new Headers(event.request.headers);
if (token) {
modifiedHeaders.append('Authorization',token)
}
const authReq = new Request(event.request,{headers: modifiedHeaders,mode: 'cors' });
event.respondWith((async () => fetch(authReq))());
}
// Intercept all fetch requests and add the auth header
self.addEventListener('fetch',addAuthHeader);
registerServiceWorker.js
register(`service-worker.js`,{
ready() {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details,...'
)
},registered() {
console.log('Service worker has been registered.')
},cached() {
console.log('Content has been cached for offline use.')
},updatefound() {
console.log('New content is downloading.')
},updated() {
console.log('New content is available; Refresh...')
setTimeout(() => {
window.location.reload();
},1000)
},offline() {
console.log('No internet connection found. App is running in offline mode.')
},error(error) {
console.error('Error during service worker registration:',error)
}
})
所以这一切都归结为:新的应用程序版本 -> 用户因为令牌丢失而注销。
有没有办法将令牌变量“移交”给新的 service-worker.js?
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。