workbox-routing
Summary
- Types
 - Methods
 
Types
NavigationRoute
NavigationRoute makes it easy to create a workbox-routing.Route that matches for browser [navigation requests]https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests.
It will only match incoming Requests whose https://fetch.spec.whatwg.org/#concept-request-mode|mode is set to navigate.
You can optionally only apply this route to a subset of navigation requests by using one or both of the denylist and allowlist parameters.
Properties
function
If both
denylistandallowlistare provided, thedenylistwill take precedence and the request will not match this route.The regular expressions in
allowlistanddenylistare matched against the concatenated [pathname]https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathnameand [search]https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/searchportions of the requested URL.Note: These RegExps may be evaluated against every destination URL during a navigation. Avoid using complex RegExps, or else your users may see delays when navigating your site.
The
constructorfunction looks like:(handler: RouteHandler, options?: NavigationRouteMatchOptions) => {...}A callback function that returns a Promise resulting in a Response.
NavigationRouteMatchOptions optional
RouteHandlerObject optional
HTTPMethod
function
The
setCatchHandlerfunction looks like:(handler: RouteHandler) => {...}A callback function that returns a Promise resolving to a Response
NavigationRouteMatchOptions
Properties
RegExp[] optional
RegExp[] optional
RegExpRoute
RegExpRoute makes it easy to create a regular expression based workbox-routing.Route.
For same-origin requests the RegExp only needs to match part of the URL. For requests against third-party servers, you must define a RegExp that matches the start of the URL.
Properties
- constructor
function
If the regular expression contains [capture groups]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references, the captured values will be passed to theworkbox-routing~handlerCallbackparamsargument.The
constructorfunction looks like:(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod) => {...}- regExp
RegExp
The regular expression to match against URLs.
 - handler
A callback function that returns a Promise resulting in a Response.
 - method
HTTPMethod optional
 
- returns
 
 - catchHandler
RouteHandlerObject optional
 - handler
 - match
 - method
HTTPMethod
 - setCatchHandler
function
The
setCatchHandlerfunction looks like:(handler: RouteHandler) => {...}- handler
A callback function that returns a Promise resolving to a Response
 
 
Route
A Route consists of a pair of callback functions, "match" and "handler". The "match" callback determine if a route should be used to "handle" a request by returning a non-falsy value if it can. The "handler" callback is called when there is a match and should return a Promise that resolves to a Response.
Properties
- constructor
function
Constructor for Route class.
The
constructorfunction looks like:(match: RouteMatchCallback, handler: RouteHandler, method?: HTTPMethod) => {...}- match
A callback function that determines whether the route matches a given
fetchevent by returning a non-falsy value. - handler
A callback function that returns a Promise resolving to a Response.
 - method
HTTPMethod optional
 
- returns
 
 - catchHandler
RouteHandlerObject optional
 - handler
 - match
 - method
HTTPMethod
 - setCatchHandler
function
The
setCatchHandlerfunction looks like:(handler: RouteHandler) => {...}- handler
A callback function that returns a Promise resolving to a Response
 
 
Router
The Router can be used to process a FetchEvent using one or more workbox-routing.Route, responding with a Response if a matching route exists.
If no route matches a given a request, the Router will use a "default" handler if one is defined.
Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to gracefully deal with issues and respond with a Request.
If a request matches multiple routes, the earliest registered route will be used to respond to the request.
Properties
- constructor
function
Initializes a new Router.
The
constructorfunction looks like:() => {...}- returns
 
 - routes
Map<HTTPMethodRoute[]>
 - addCacheListener
function
Adds a message event listener for URLs to cache from the window. This is useful to cache resources loaded on the page prior to when the service worker started controlling it.
The format of the message data sent from the window should be as follows. Where the
urlsToCachearray may consist of URL strings or an array of URL string +requestInitobject (the same as you'd pass tofetch()).{ type: 'CACHE_URLS', payload: { urlsToCache: [ './script1.js', './script2.js', ['./script3.js', {mode: 'no-cors'}], ], }, }The
addCacheListenerfunction looks like:() => {...} - addFetchListener
function
Adds a fetch event listener to respond to events when a route matches the event's request.
The
addFetchListenerfunction looks like:() => {...} - findMatchingRoute
function
Checks a request and URL (and optionally an event) against the list of registered routes, and if there's a match, returns the corresponding route along with any params generated by the match.
The
findMatchingRoutefunction looks like:(options: RouteMatchCallbackOptions) => {...}- options
 
- returns
object
An object with
routeandparamsproperties. They are populated if a matching route was found orundefinedotherwise. 
 - handleRequest
function
Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler.
The
handleRequestfunction looks like:(options: object) => {...}- options
object
- event
ExtendableEvent
The event that triggered the request.
 - request
Request
The request to handle.
 
 
- returns
Promise<Response>
A promise is returned if a registered route can handle the request. If there is no matching route and there's no
defaultHandler,undefinedis returned. 
 - registerRoute
function
Registers a route with the router.
The
registerRoutefunction looks like:(route: Route) => {...}- route
The route to register.
 
 - setCatchHandler
function
If a Route throws an error while handling a request, this
handlerwill be called and given a chance to provide a response.The
setCatchHandlerfunction looks like:(handler: RouteHandler) => {...}- handler
A callback function that returns a Promise resulting in a Response.
 
 - setDefaultHandler
function
Define a default
handlerthat's called when no routes explicitly match the incoming request.Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
Without a default handler, unmatched requests will go against the network as if there were no service worker present.
The
setDefaultHandlerfunction looks like:(handler: RouteHandler, method?: HTTPMethod) => {...}- handler
A callback function that returns a Promise resulting in a Response.
 - method
HTTPMethod optional
 
 - unregisterRoute
function
Unregisters a route with the router.
The
unregisterRoutefunction looks like:(route: Route) => {...}- route
The route to unregister.
 
 
Methods
registerRoute
          
          
            workbox-routing.registerRoute(
        capture:
  string | RegExp | RouteMatchCallback | Route,
        handler?:
  RouteHandler,
        method?:
  HTTPMethod,
      
    )
          
        Easily register a RegExp, string, or function with a caching strategy to a singleton Router instance.
This method will generate a Route for you if needed and call workbox-routing.Router#registerRoute.
Parameters
- capture
string | RegExp | RouteMatchCallback | Route
If the capture param is a
Route, all other arguments will be ignored. - handler
RouteHandler optional
 - method
HTTPMethod optional
 
Returns
The generated
Route.
setCatchHandler
          
          
            workbox-routing.setCatchHandler(
        handler:
  RouteHandler,
      
    )
          
        If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response.
Parameters
- handler
A callback function that returns a Promise resulting in a Response.
 
setDefaultHandler
          
          
            workbox-routing.setDefaultHandler(
        handler:
  RouteHandler,
      
    )
          
        Define a default handler that's called when no routes explicitly match the incoming request.
Without a default handler, unmatched requests will go against the network as if there were no service worker present.
Parameters
- handler
A callback function that returns a Promise resulting in a Response.