-
Because I often use it offline, I hope to increase the offline cache of ServerWorker. Object.assign(self,
{
CACHE_DB: caches.open(self.registration.scope.split(/\//)[2]),
CACHE_PATH: self.registration.scope,
getHeaders(headers) {
var objs = {};
headers.forEach((a, b) => objs[b] = a);
return objs;
},
postMessage(str) {
self.clients.matchAll().then(WindowClients => WindowClients.forEach(Clients => {
if (Clients.visibilityState == 'visible') {
Clients.postMessage(str);
}
}))
}
});
Object.entries({
install(event) {
console.log(event.type);
return self.skipWaiting(); //跳过等待
},
activate(event) {
console.log(event.type);
return self.skipWaiting(); //跳过等待
},
fetch(event) {
if (/GET/.test(event.request.method)) {
var url = event.request.url;
//拦截请求 event.request 一个请求对象
return event.respondWith(new Promise(async resolve => {
if (location.protocol != url.slice(0,5)) url = url.replace(url.slice(0,6), location.protocol);
var CACHE = await CACHE_DB,
response = await CACHE.match(event.request);
if (navigator.onLine) {
//联网状态
var headers = response&&getHeaders(response);
var key = Date.name.toLocaleLowerCase();
if(url.includes(CACHE_PATH)&&headers&&headers[key]&&new Date() - Date.parse(headers[key])>24*3600*1000){
//update
response = null;
}
if (!response) {
response = await fetch(event.request);
// /cdn/.test(url)
if(response&&response.status == 200){
//pass 404
CACHE.put(event.request, response.clone());
}
}
}
resolve(response);
}));
}
},
message(event) {
console.log(event.data);
}
}).forEach(
entry => addEventListener(entry[0], entry[1])
); |
Beta Was this translation helpful? Give feedback.
Answered by
yin1999
Aug 30, 2023
Replies: 1 comment
-
This is a supported feature. Unfortunately, this feature requires an MDN Plus subscription, which is not available in Mainland China. If you do need this feature. You could follow the setup steps: clone mdn/content and mdn/translated-content, and run |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
nenge123
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a supported feature. Unfortunately, this feature requires an MDN Plus subscription, which is not available in Mainland China.
If you do need this feature. You could follow the setup steps: clone mdn/content and mdn/translated-content, and run
yarn start
to start a local server. You can get an experience similar to online documentation.