这是我的服务人员:
'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);
})
);
}
});
它是标准的脱机缓存服务工作者: https://googlechrome.github.io/samples/service-worker/custom-offline-page/
我在控制台中没有错误。
在Android Chrome上,将页面添加到主页工作正常(我有一个定义图标和网址的清单)。但是,当我关闭手机上的连接时,我收到一条错误消息:
Not Found
The requested URL/offline.html was not found on this server.
我该如何解决这个问题?
答案 0 :(得分:0)
我认为这是我配置域名的方式 - 我已将/ domain映射到我的/ www域名。我更改了const OFFLINE_URL ='offline.html';至const OFFLINE_URL ='https://example.com/offline.html';它起作用了。使用绝对URL始终有效。