Router

Adds a friendly API on top of the router from the workbox-routing module.

Examples

How to define a simple route with caching strategy.

const workboxSW = new WorkboxSW();
workboxSW.router.registerRoute('/about',
 workboxSW.strategies.cacheFirst());

How to define a simple route with custom caching strategy.

const workboxSW = new WorkboxSW();
workboxSW.router.registerRoute('/about', (args) => {
  // The requested URL
  console.log(args.url);

  // The FetchEvent to handle
  console.log(args.event);

  // The parameters from the matching route (Commonly
  // used with Regex / Express routes).
  console.log(args.params);

  // Return a promise that resolves with a Response.
  return fetch(args.url);
}));

Constructor

new Router(revisionedCacheName, handleFetch)

Constructs a light wrapper on top of the underlying Router.

Parameters
revisionedCacheName String

The cache name used for entries cached via precache().

handleFetch boolean

Determines if the router should handle fetch events.

Instance Methods

this.registerNavigationRoute(url, options)

A shortcut used to register a NavigationRoute instance that will respond to navigation requests using a cache entry for url.

This is useful when following the App Shell pattern, in which the previously cached shell is returned for all navigations.

The url value should correspond to an entry that's already in the cache, perhaps a URL that is managed by precache(). Using a URL that isn't already cached will lead to failed navigations.

Parameters
url String

The URL of the already cached HTML resource.

options Object (Optional)
Properties
blacklist Array.<RegExp> (Optional)

Defaults to an empty blacklist.

whitelist Array.<RegExp> (Optional)

Defaults to [/./], which will match all request URLs.

cacheName String (Optional)

The name of the cache which contains the cached response for url. Defaults to the name of the cache used by precache().

this.registerRoute(capture, handler, method) Route

Parameters
capture String | RegExp | matchCallback

The capture for a route can be one of three types:

  1. An Express-style route, like '/path/to/:anything' for same-origin or 'https://cross-origin.com/path/to/:anything' for cross-origin routes.
  2. A regular expression that will be tested against request URLs. For cross-origin routes, you must use a RegExp that matches the start of the full URL, like new RegExp('https://cross-origin\.com/').
  3. A function which is passed the URL and FetchEvent, and should returns a truthy value if the route matches.
handler function | Handler

The handler to use to provide a response if the route matches. The handler argument is ignored if you pass in a Route object, otherwise it's required.

method String (Optional) GET

Only match requests that use this HTTP method.

  • Defaults to 'GET'.
Returns Route

The Route object that was registered.