[英]Service Worker not caching html file
This is my service worker: 这是我的服务人员:
'use strict';
const CACHE_VERSION = 1;
let CURRENT_CACHES = {
offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'offline.html';
function createCacheBustedRequest(url) {
let request = new Request(url, {cache: 'reload'});
if ('cache' in request) {
return request;
}
let bustedUrl = new URL(url, self.location.href);
bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
return new Request(bustedUrl);
}
self.addEventListener('install', event => {
event.waitUntil(
fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
return caches.open(CURRENT_CACHES.offline).then(function(cache) {
return cache.put(OFFLINE_URL, response);
});
})
);
});
self.addEventListener('activate', event => {
let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
return CURRENT_CACHES[key];
});
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (expectedCacheNames.indexOf(cacheName) === -1) {
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' &&
event.request.headers.get('accept').includes('text/html'))) {
console.log('Handling fetch event for', event.request.url);
event.respondWith(
fetch(createCacheBustedRequest(event.request.url)).catch(error => {
console.log('Fetch failed; returning offline page instead.', error);
return caches.match(OFFLINE_URL);
})
);
}
});
It's the standard offline cache service worker: https://googlechrome.github.io/samples/service-worker/custom-offline-page/ 它是标准的离线缓存服务工作者: https : //googlechrome.github.io/samples/service-worker/custom-offline-page/
I get no error in console. 我在控制台中没有错误。
On Android Chrome, adding the page to home page works fine (I've a manifest that defines the icon and URL). 在Android Chrome浏览器上,将页面添加到主页可以正常工作(我有一个定义图标和URL的清单)。 However, when I turn off my connectivity on the phone, I get an error message:
但是,当我关闭手机的连接时,会收到错误消息:
Not Found
The requested URL/offline.html was not found on this server.
How do I fix this? 我该如何解决?
I think it's in the way I configured my domains - I have mapped my / domain to my /www domain. 我认为这是我配置域的方式-我已将/域映射到/ www域。 I changed the const OFFLINE_URL = 'offline.html';
我更改了const OFFLINE_URL ='offline.html'; to const OFFLINE_URL = ' https://example.com/offline.html ';
到const OFFLINE_URL =' https: //example.com/offline.html'; and it worked.
而且有效。 Using an absolute URL works all the time.
始终使用绝对URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.