如果没有网络连接,Service Worker (sw.js) 应该总是 return offline.html 文档
Service Worker (sw.js) should always return offline.html document if there is no network connection
我遇到了部分工作的服务工作者的问题。清单为将网站添加到主屏幕的用户正确定义了 start_url
(https://example.com/start.html),start.html 和 offline.html 也被正确缓存,两者都是在浏览器没有互联网连接时可用。
如果用户下线(无网络连接),服务工作人员会成功提供 https://example.com/start.html 和 https: //example.com/offline.html -- 但如果用户尝试打开其他任何东西(例如 https://example.com/something.html) 浏览器抛出“无法访问站点”错误消息。
我真正需要的是,如果没有网络连接,service worker 总是 returns offline.html 缓存文档,无论url 用户正尝试到达。
换句话说,问题是在没有网络连接的情况下,Service Worker 没有正确地为用户的请求服务 offline.html(无论找到什么解决方案,它也需要缓存 start.html 清单的 start_url).
这是我当前的代码:
manifest.json
{
"name": "My Basic Example",
"short_name": "Example",
"icons": [
{
"src": "https://example.com/static/ico/manifest-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://example.com/static/ico/manifest-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
],
"start_url": "https://example.com/start.html",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#2196f3",
"theme_color": "#2196f3"
}
core.js
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js', {
scope: '/'
}).then(function(registration) {
}).catch(function(err) {
});
navigator.serviceWorker.ready.then(function(registration) {
});
}
sw.js
const PRECACHE = 'cache-v1';
const RUNTIME = 'runtime';
const PRECACHE_URLS = [
'/offline.html',
'/start.html'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting())
);
});
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
})
.then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
})
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', event => {
if(event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if(cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
}
});
有什么想法吗?谢谢!
您的大部分代码都按预期工作,但您需要检查用户是否在请求 start.html
。我从 Create an offline fallback page 中获取了代码并对其进行了修改以满足您的要求。
// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const START_URL = "start.html";
const OFFLINE_URL = "offline.html";
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
// Setting {cache: 'reload'} in the new request will ensure that the
// response isn't fulfilled from the HTTP cache; i.e., it will be from
// the network.
await Promise.all([
cache.add(new Request(OFFLINE_URL, { cache: "reload" })),
cache.add(new Request(START_URL, { cache: "reload" })),
]);
})()
);
// Force the waiting service worker to become the active service worker.
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
// Enable navigation preload if it's supported.
// See https://developers.google.com/web/updates/2017/02/navigation-preload
if ("navigationPreload" in self.registration) {
await self.registration.navigationPreload.enable();
}
})()
);
// Tell the active service worker to take control of the page immediately.
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
// We only want to call event.respondWith() if this is a navigation request
// for an HTML page.
if (event.request.mode === "navigate") {
event.respondWith(
(async () => {
try {
// First, try to use the navigation preload response if it's supported.
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
// Always try the network first.
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
console.log("Fetch failed; returning cached page instead.", error);
const cache = await caches.open(CACHE_NAME);
if (event.request.url.includes(START_URL)) {
return await cache.match(START_URL);
}
return await cache.match(OFFLINE_URL);
}
})()
);
}
// If our if() condition is false, then this fetch handler won't intercept the
// request. If there are any other fetch handlers registered, they will get a
// chance to call event.respondWith(). If no fetch handlers call
// event.respondWith(), the request will be handled by the browser as if there
// were no service worker involvement.
});
有一点需要注意,一旦 start.html
在第一次安装 service worker 时被缓存,它将 不会 再次更新,直到 service worker 被安装更新。这意味着您的用户在离线并加载您的应用程序时可能会随时看到 old/outdated start.html
。您可能想对 start.html
.
使用 network first strategy
你可以试试working demo and source
我遇到了部分工作的服务工作者的问题。清单为将网站添加到主屏幕的用户正确定义了 start_url
(https://example.com/start.html),start.html 和 offline.html 也被正确缓存,两者都是在浏览器没有互联网连接时可用。
如果用户下线(无网络连接),服务工作人员会成功提供 https://example.com/start.html 和 https: //example.com/offline.html -- 但如果用户尝试打开其他任何东西(例如 https://example.com/something.html) 浏览器抛出“无法访问站点”错误消息。
我真正需要的是,如果没有网络连接,service worker 总是 returns offline.html 缓存文档,无论url 用户正尝试到达。
换句话说,问题是在没有网络连接的情况下,Service Worker 没有正确地为用户的请求服务 offline.html(无论找到什么解决方案,它也需要缓存 start.html 清单的 start_url).
这是我当前的代码:
manifest.json
{
"name": "My Basic Example",
"short_name": "Example",
"icons": [
{
"src": "https://example.com/static/ico/manifest-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://example.com/static/ico/manifest-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
],
"start_url": "https://example.com/start.html",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#2196f3",
"theme_color": "#2196f3"
}
core.js
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js', {
scope: '/'
}).then(function(registration) {
}).catch(function(err) {
});
navigator.serviceWorker.ready.then(function(registration) {
});
}
sw.js
const PRECACHE = 'cache-v1';
const RUNTIME = 'runtime';
const PRECACHE_URLS = [
'/offline.html',
'/start.html'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting())
);
});
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
})
.then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
})
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', event => {
if(event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if(cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
}
});
有什么想法吗?谢谢!
您的大部分代码都按预期工作,但您需要检查用户是否在请求 start.html
。我从 Create an offline fallback page 中获取了代码并对其进行了修改以满足您的要求。
// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const START_URL = "start.html";
const OFFLINE_URL = "offline.html";
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
// Setting {cache: 'reload'} in the new request will ensure that the
// response isn't fulfilled from the HTTP cache; i.e., it will be from
// the network.
await Promise.all([
cache.add(new Request(OFFLINE_URL, { cache: "reload" })),
cache.add(new Request(START_URL, { cache: "reload" })),
]);
})()
);
// Force the waiting service worker to become the active service worker.
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
// Enable navigation preload if it's supported.
// See https://developers.google.com/web/updates/2017/02/navigation-preload
if ("navigationPreload" in self.registration) {
await self.registration.navigationPreload.enable();
}
})()
);
// Tell the active service worker to take control of the page immediately.
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
// We only want to call event.respondWith() if this is a navigation request
// for an HTML page.
if (event.request.mode === "navigate") {
event.respondWith(
(async () => {
try {
// First, try to use the navigation preload response if it's supported.
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
// Always try the network first.
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
console.log("Fetch failed; returning cached page instead.", error);
const cache = await caches.open(CACHE_NAME);
if (event.request.url.includes(START_URL)) {
return await cache.match(START_URL);
}
return await cache.match(OFFLINE_URL);
}
})()
);
}
// If our if() condition is false, then this fetch handler won't intercept the
// request. If there are any other fetch handlers registered, they will get a
// chance to call event.respondWith(). If no fetch handlers call
// event.respondWith(), the request will be handled by the browser as if there
// were no service worker involvement.
});
有一点需要注意,一旦 start.html
在第一次安装 service worker 时被缓存,它将 不会 再次更新,直到 service worker 被安装更新。这意味着您的用户在离线并加载您的应用程序时可能会随时看到 old/outdated start.html
。您可能想对 start.html
.
你可以试试working demo and source