workbox-core

Workbox has been built to be modular, allowing developers to select the pieces they want to use without forcing them to download everything in a single file.

There is however overlap between modules, for example, each module will like need to interact with the console, throw meaningful errors and make use of the network or cache. To avoid each module implementing the same logic, workbox-core contains this common code which each module relies on.

This module does provide some functionality to developers, but beyond log levels and caching, workbox-core offers internal logic to each module, rather than the end developer.

View and Change the Default Cache Names

Workbox defines it's caches via cacheNames:

import {cacheNames} from 'workbox-core';

console.log(cacheNames.precache);
console.log(cacheNames.runtime);
console.log(cacheNames.googleAnalytics);

These cache names are constructed in the format of a prefix, a name and suffix, where the name changes based on the use of the cache.

<prefix>-<cache-id>-<suffix>

You can change these default names by altering all or some of the values passed to setCacheNameDetails().

import {cacheNames, setCacheNameDetails} from 'workbox-core';

setCacheNameDetails({
  prefix: 'my-app',
  suffix: 'v1',
  precache: 'install-time',
  runtime: 'run-time',
  googleAnalytics: 'ga',
});

// Will print 'my-app-install-time-v1'
console.log(cacheNames.precache);

// Will print 'my-app-run-time-v1'
console.log(cacheNames.runtime);

// Will print 'my-app-ga-v1'
console.log(cacheNames.googleAnalytics);

The main use case for the prefix and suffix is that if you use Workbox for multiple projects and use the same localhost port for each project, setting a custom prefix for each module will prevent the caches from conflicting with each other.

Clients Claim

Some developers want to be able to publish a new service worker and have it control already-open web pages as soon as it activates, which will not happen by default.

If you find yourself wanting this behavior, workbox-core provides a helper method:

import {clientsClaim} from 'workbox-core';

// This clientsClaim() should be at the top level
// of your service worker, not inside of, e.g.,
// an event handler.
clientsClaim();

The clientsClaim() method in workbox-core automatically adds an activate event listener to your service worker, and inside of it, calls self.clients.claim(). Calling self.clients.claim() before the current service worker activates will lead to a runtime exception, and workbox-core's wrapper helps ensure that you call it at the right time.

The skipWaiting wrapper is deprecated

Previous to Workbox v6, developers were also encouraged to use the skipWaiting() method from workbox-core. However, this method offered little value beyond what developers would get if they called self.skipWaiting() explicitly.

Because the legacy workbox-core wrapper also registered an install event handler in which self.skipWaiting() was called, the wrapper would not behave as expected if it were called inside of another event handler, like message, after installation had already completed.

For these reasons, workbox-core's skipWaiting() is deprecated, and developers should switch to calling self.skipWaiting() directly. Unlike with self.clients.claim(), self.skipWaiting() will not throw an exception if called at the "wrong" time, so there is no need to wrap it in an event handler.

Types

CacheDidUpdateCallback()

workbox-core.CacheDidUpdateCallback(
  param: CacheDidUpdateCallbackParam,
)

Parameters

Returns

  • Promise<void>

CacheDidUpdateCallbackParam

Properties

  • cacheName

    string

  • event

    ExtendableEvent

  • newResponse

    Response

  • oldResponse

    Response optional

  • request

    Request

  • state

    MapLikeObject optional

CachedResponseWillBeUsedCallback()

workbox-core.CachedResponseWillBeUsedCallback(
  param: CachedResponseWillBeUsedCallbackParam,
)

Returns

  • Promise<void|Response>

CachedResponseWillBeUsedCallbackParam

Properties

  • cacheName

    string

  • cachedResponse

    Response optional

  • event

    ExtendableEvent

  • matchOptions

    CacheQueryOptions optional

  • request

    Request

  • state

    MapLikeObject optional

CacheKeyWillBeUsedCallback()

workbox-core.CacheKeyWillBeUsedCallback(
  param: CacheKeyWillBeUsedCallbackParam,
)

Returns

  • Promise<string|Request>

CacheKeyWillBeUsedCallbackParam

Properties

  • event

    ExtendableEvent

  • mode

    string

  • params

    any optional

  • request

    Request

  • state

    MapLikeObject optional

CacheWillUpdateCallback()

workbox-core.CacheWillUpdateCallback(
  param: CacheWillUpdateCallbackParam,
)

Returns

  • Promise<void|Response>

CacheWillUpdateCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • response

    Response

  • state

    MapLikeObject optional

FetchDidFailCallback()

workbox-core.FetchDidFailCallback(
  param: FetchDidFailCallbackParam,
)

Parameters

Returns

  • Promise<void>

FetchDidFailCallbackParam

Properties

  • error

    Error

  • event

    ExtendableEvent

  • originalRequest

    Request

  • request

    Request

  • state

    MapLikeObject optional

FetchDidSucceedCallback()

workbox-core.FetchDidSucceedCallback(
  param: FetchDidSucceedCallbackParam,
)

Returns

  • Promise<Response>

FetchDidSucceedCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • response

    Response

  • state

    MapLikeObject optional

HandlerCallbackOptions

HandlerDidCompleteCallback()

workbox-core.HandlerDidCompleteCallback(
  param: HandlerDidCompleteCallbackParam,
)

Returns

  • Promise<void>

HandlerDidCompleteCallbackParam

Properties

  • error

    Error optional

  • event

    ExtendableEvent

  • request

    Request

  • response

    Response optional

  • state

    MapLikeObject optional

HandlerDidErrorCallback()

workbox-core.HandlerDidErrorCallback(
  param: HandlerDidErrorCallbackParam,
)

Returns

  • Promise<Response>

HandlerDidErrorCallbackParam

Properties

  • error

    Error

  • event

    ExtendableEvent

  • request

    Request

  • state

    MapLikeObject optional

HandlerDidRespondCallback()

workbox-core.HandlerDidRespondCallback(
  param: HandlerDidRespondCallbackParam,
)

Returns

  • Promise<void>

HandlerDidRespondCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • response

    Response optional

  • state

    MapLikeObject optional

HandlerWillRespondCallback()

workbox-core.HandlerWillRespondCallback(
  param: HandlerWillRespondCallbackParam,
)

Returns

  • Promise<Response>

HandlerWillRespondCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • response

    Response

  • state

    MapLikeObject optional

HandlerWillStartCallback()

workbox-core.HandlerWillStartCallback(
  param: HandlerWillStartCallbackParam,
)

Returns

  • Promise<void>

HandlerWillStartCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • state

    MapLikeObject optional

ManualHandlerCallback()

workbox-core.ManualHandlerCallback(
  options: ManualHandlerCallbackOptions,
)

The "handler" callback is invoked whenever a Router matches a URL/Request to a Route via its RouteMatchCallback. This handler callback should return a Promise that resolves with a Response.

If a non-empty array or object is returned by the RouteMatchCallback it will be passed in as this handler's options.params argument.

Parameters

Returns

  • Promise<Response>

ManualHandlerCallbackOptions

Options passed to a ManualHandlerCallback function.

Properties

  • event

    ExtendableEvent

  • request

    string|Request

MapLikeObject

PluginState

Using a plain MapLikeObject for now, but could extend/restrict this in the future.

RequestWillFetchCallback()

workbox-core.RequestWillFetchCallback(
  param: RequestWillFetchCallbackParam,
)

Returns

  • Promise<Request>

RequestWillFetchCallbackParam

Properties

  • event

    ExtendableEvent

  • request

    Request

  • state

    MapLikeObject optional

RouteHandler

Either a RouteHandlerCallback or a RouteHandlerObject. Most APIs in workbox-routing that accept route handlers take either.

RouteHandlerCallback()

workbox-core.RouteHandlerCallback(
  options: RouteHandlerCallbackOptions,
)

The "handler" callback is invoked whenever a Router matches a URL/Request to a Route via its RouteMatchCallback. This handler callback should return a Promise that resolves with a Response.

If a non-empty array or object is returned by the RouteMatchCallback it will be passed in as this handler's options.params argument.

Parameters

Returns

  • Promise<Response>

RouteHandlerCallbackOptions

Options passed to a RouteHandlerCallback function.

Properties

  • event

    ExtendableEvent

  • params

    string[]|MapLikeObject optional

  • request

    Request

  • url

    URL

RouteHandlerObject

An object with a handle method of type RouteHandlerCallback.

A Route object can be created with either an RouteHandlerCallback function or this RouteHandler object. The benefit of the RouteHandler is it can be extended (as is done by the workbox-strategies package).

Properties

RouteMatchCallback()

workbox-core.RouteMatchCallback(
  options: RouteMatchCallbackOptions,
)

The "match" callback is used to determine if a Route should apply for a particular URL and request. When matching occurs in response to a fetch event from the client, the event object is also supplied. However, since the match callback can be invoked outside of a fetch event, matching logic should not assume the event object will always be available. If the match callback returns a truthy value, the matching route's RouteHandlerCallback will be invoked immediately. If the value returned is a non-empty array or object, that value will be set on the handler's options.params argument.

Parameters

Returns

  • any

RouteMatchCallbackOptions

Options passed to a RouteMatchCallback function.

Properties

  • event

    ExtendableEvent

  • request

    Request

  • sameOrigin

    boolean

  • url

    URL

WorkboxPlugin

An object with optional lifecycle callback properties for the fetch and cache operations.

Properties

WorkboxPluginCallbackParam

Properties

cacheNames

Get the current cache names and prefix/suffix used by Workbox.

cacheNames.precache is used for precached assets, cacheNames.googleAnalytics is used by workbox-google-analytics to store analytics.js, and cacheNames.runtime is used for everything else.

cacheNames.prefix can be used to retrieve just the current prefix value. cacheNames.suffix can be used to retrieve just the current suffix value.

Type

object

Properties

  • googleAnalytics

    string

  • precache

    string

  • prefix

    string

  • runtime

    string

  • suffix

    string

Methods

clientsClaim()

workbox-core.clientsClaim()

Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting().

copyResponse()

workbox-core.copyResponse(
  response: Response,
  modifier?: function,
)

Allows developers to copy a response and modify its headers, status, or statusText values (the values settable via a [ResponseInit]https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax object in the constructor). To modify these values, pass a function as the second argument. That function will be invoked with a single object with the response properties {headers, status, statusText}. The return value of this function will be used as the ResponseInit for the new Response. To change the values either modify the passed parameter(s) and return it, or return a totally new object.

This method is intentionally limited to same-origin responses, regardless of whether CORS was used or not.

Parameters

  • response

    Response

  • modifier

    function optional

    The modifier parameter looks like:

    (responseInit: ResponseInit)=>ResponseInit

    • responseInit

      ResponseInit

    • returns

      ResponseInit

Returns

  • Promise<Response>

registerQuotaErrorCallback()

workbox-core.registerQuotaErrorCallback(
  callback: Function,
)

Adds a function to the set of quotaErrorCallbacks that will be executed if there's a quota error.

Parameters

  • callback

    Function

setCacheNameDetails()

workbox-core.setCacheNameDetails(
  details: PartialCacheNameDetails,
)

Modifies the default cache names used by the Workbox packages. Cache names are generated as <prefix>-<Cache Name>-<suffix>.

Parameters

  • details

    PartialCacheNameDetails

skipWaiting()

workbox-core.skipWaiting()

This method is deprecated, and will be removed in Workbox v7.

Calling self.skipWaiting() is equivalent, and should be used instead.