简体   繁体   中英

Rewrite URL offline when using a service worker

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.

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?

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.

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'],
}

This shouldn't interfere with anything that sw-precache is doing, as it will just be used as fallback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM