我正在使用由名为 sw-precache 的 Nodejs 插件生成的服务工作线程来制作具有离线功能的 Web 应用程序。 。一切正常,我可以离线访问 html 文件或图像。
但是,由于您没有可能的服务器端语言,有没有办法像 .htaccess
文件一样在客户端重写 url?就像当没有文件与 url 匹配时显示“404 页面未找到”页面一样?我知道可以使用 Javascript 或元标记进行重定向,但是重写 url 吗?
最佳答案
默认情况下,当请求的 URL 是它已缓存的资源的 URL 时,sw-precache
将仅响应 fetch
事件。如果有人导航到不存在网页的 URL,则 sw-precache
将不会响应 fetch
事件。
这确实意味着您有机会在附加的 fetch
事件处理程序中运行自己的代码,该事件处理程序可以实现自定义行为,例如在以下情况下返回 404.html
页面:用户在离线状态下导航到不存在的页面。您需要跨越几个障碍,但具体操作方法如下:
// In custom-offline-import.js:
self.addEventListener('fetch', event => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request)
.catch(() => caches.match('404.html', {ignoreSearch: true}))
// {ignoreSearch: true} is needed, since sw-precache appends a search
// parameter with versioning information.
);
}
});
// In your sw-precache config:
{
// Make sure 404.html is picked up in one of the glob patterns:
staticFileGlobs: ['404.html'],
// See https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
importScripts: ['custom-offline-import.js'],
}
这不应干扰 sw-precache
正在执行的任何操作,因为它将仅用作后备。
关于javascript - 使用 Service Worker 时离线重写 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42491242/