使用服务工作者时脱机重写URL [英] Rewrite URL offline when using a service worker
问题描述
我正在使用由名为 sw-预缓存.一切正常,我可以脱机访问html文件或图像.
I am making a web application with offline capabilities using a service worker generated by a Nodejs plugin called sw-precache. Everything works fine and I do have access to the html files or images offline.
但是,既然您不可能使用服务器端语言,是否有办法像.htaccess
文件那样重写客户端的url?像没有文件匹配url时显示找不到404页"页面一样?我知道可以使用Javascript或元标记进行重定向,但可以重写网址吗?
But then, since you have no server-side language possible, is there a way to rewrite url client-side like an .htaccess
file would do? Like showing a "404 Page not found" page when no file matches the url? I know that redirections are possible using Javascript or meta tags, but rewriting the url?
推荐答案
默认情况下,当请求的URL是已缓存资源的URL时,sw-precache
仅响应fetch
事件.如果有人导航到不存在的网页的URL,则sw-precache
将不会响应fetch
事件.
By default, sw-precache
will only respond to fetch
events when the URL being requested is a URL for a resource that it has cached. If someone navigations to a URL for a non-existent web page, then sw-precache
won't respond to the fetch
event.
这确实意味着您有机会在可以实现自定义行为的其他fetch
事件处理程序中运行自己的代码,例如当用户离线时导航到不存在的页面时返回404.html
页面.您需要跳几圈,但这是这样做的方法:
That does mean that you have a chance to run your own code in an additional fetch
event handler that could implement custom behavior, like returning a 404.html
page when a user navigates to a non-existent page while offline. You need to jump through a couple of hoops, but here's how to do it:
// 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
所做的任何事情,因为它将仅用作后备.
This shouldn't interfere with anything that sw-precache
is doing, as it will just be used as fallback.
这篇关于使用服务工作者时脱机重写URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!