Skip to content

Releases: GoogleChrome/workbox

Workbox v4.0.0-beta.2

30 Jan 17:03
Compare
Choose a tag to compare
Workbox v4.0.0-beta.2 Pre-release
Pre-release

The latest beta release of Workbox v4 includes the following developer-visible changes, in addition to all the changes from the previous pre-releases.

🎉 What's New?

workbox-window

  • The Workbox constructor function signature has changed to accept an optional scriptVersion option. To support this new option (and other future options) the constructor now accepts a single object argument [#1861].
// Old way
new Workbox(scriptURL, registerOptions);

// New way 
new Workbox({
  scriptUrl,
  scriptVersion,
  registerOptions,
});
  • The properties .active and .controlling have been added to the Workbox class. These are promises which will resolve as soon as Workbox has a reference to a service working in the corresponding state (active or controlling) with a matching scriptURL (and optionally scriptVersion, if used). These are similar to the navigator.serviceWorker.ready promise, but when using scriptVersion you can be sure they won't resolve until the correct version of the script is active/controlling [#1861].

  • Workbox event listeners are now always called with an Event-like object (i.e. they have a .type, .target properties), to more closely match how native event listeners work. In the future when all browsers support contructable EventTarget, these will be native Event objects [#1861].

// Old way
myWorkbox.addEventListener('activated', (sw) => {
  // Do something with `sw`.
});

// New way 
myWorkbox.addEventListener('activated', (event) => {
  // The activated service worker is at `event.sw`.
  // And the underlying event that triggered this is at `event.originalEvent`.
});
  • The controlling event is now dispatched prior to the activated event, which correctly matches the ordering of when the controllerchange and statechange events fire in the service worker lifecycle. [#1861]

workbox-routing

  • The workbox.routing.Router#addCacheListener() method has updated the format off messages it can receive from the window to cache. Previously it would accept an array of URL strings, now it can also accept an array of URL strings or arrays in the form of [url, requestInit]. This is useful if you need to override the default request mode [#1851]

Build tools

  • Support for a new boolean configuration option, cleanupOutdatedCaches, has been added to the GenerateSW mode of all of the build tools. It defaults to false. When set to true, a call to workbox.precaching.cleanupOutdatedCaches() will automatically be added to your generated service worker, which will in turn delete any out-of-date precaches no longer used by Workbox. Workbox v4 introduced a breaking change to the precache format, so developers upgrading from Workbox v3 or earlier might find this useful. [#1863]

🐛 What's Fixed?

workbox-webpack-plugin

  • In addition to swSrc being a file on file system, it can now be a webpack generated asset as well. This allows users to compile their service worker with webpack and then give it as a source to inject-manifest plugin. [#1763]

workbox-core

  • Don't set fetchOptions when request.mode is 'navigate', to work around an issue that could lead to failed navigations. [#1862]

Workbox v4.0.0-beta.1

16 Jan 01:33
Compare
Choose a tag to compare
Workbox v4.0.0-beta.1 Pre-release
Pre-release

Workbox v4.0.0-beta.1 Release Notes

The latest beta release of Workbox v4 includes the following developer-visible changes, in addition to all the changes from the previous pre-releases.

🎉 What's New?

The workbox-windowpackage

The workbox-window, a library which can be used from the context of your web page (i.e. the window global scope). It provides helpers for registering and detecting updates to your service worker. Functionality will be added over time, and we're looking for early feedback. (#1827)

You can try out workbox-window in dev mode today by adding the following module script to your HTML templates. But be sure change the URL to workbox-window.prod.mjs before deploying your code to production!

<script type="module">
// Important: change the filename to workbox-window.prod.mjs before deploying.
import {Workbox} from 'https://storage.googleapis.com/workbox-cdn/releases/4.0.0-beta.1/workbox-window.dev.mjs'

new Workbox('/sw.js').register();
</script>

For additional usage instructions and API reference, see the design doc.

Other new features:

  • workbox-cli now supports a --watch parameter. When used, it will re-run the service worker build whenever any of the files in the precache manifest change. (#1776)

  • Support for including JavaScript functions when configuring runtimeCaching in the various build tools. (#1770 and #1778)

  • The workbox-webpack-plugin will append to, rather than overwrite, any existing self.__precacheManifest value, making it easier to combine a precache manifest with the manifest generated by the plugin. (#1775)

  • A new fetchDidSucceed({request, response}) lifecycle callback has been added, allowing developers to inspect and potentially modify a response that's been retrieved from the network, prior to it being passed back to the page. (#1772)

  • The default check for whether a response is cacheable now looks explicitly for a status code of 200, rather than checking for response.ok (which is true for any status code in the range 200-209). In practice, this means that partial responses with a status code of 206 won't be inadvertently cached by default. (#1805)

  • The default injectionPointRegexp option value has been updated to exclude a leading . character, making it friendlier to developers who are bundling their own service worker files. (#1834)

  • Several under-the-hood changes have been made to Workbox's internal build and bundling structure, which should not impact developers using the default, prepackaged libraries. (#1831)

⚠️ Breaking Changes

workbox-precaching rewrite

workbox-precaching has undergone a major rewrite (#1820) to address the issues detailed in #1793. As a result, existing precached data used by Workbox prior to this beta release can't be reused, and upon registering a service worker that uses this new code, all precached data will be downloaded again.

Changes to cache keys

Entries that are precached will now store any revision information provided in the precache manifest as a special URL query parameter, __WB_REVISION__, appended to the entry's real URL. In practice, that means that a precache entry with a URL of /index.html and revision of abcd1234 would be cached with a key of /index.html?__WB_REVISION__=abcd1234.

If you are using workbox-precaching via the precacheAndRoute() interface, as most developers are, the details of looking up the correct cache key will be handled for your automatically.

If you have a need to manually retrieve a precached entry directly using caches.match(), then you have two options:

  • Use the "real" URL, and pass in the ignoreSearch parameter to caches.match(). This does not give you any guarantees about which version of the cached resource you'll retrieve.

  • Pass the "real" URL to workbox.precaching.getCacheKeyForURL(), which will return the cache key corresponding to the version of the resource cached by the current service worker. You can then pass this cache key directly to caches.match(). This is the safest approach.

Cleaning up old precached data

After upgrading to the latest Workbox v4.0.0-beta.1 release, any precached data stored by a previous version of Workbox will effectively be "abandoned". Workbox will not attempt to delete outdated precaches, as doing so involves some degree of guessing what the previous precache name was.

A new method, workbox.precaching.cleanupOutdatedCaches() can be manually called if you would like to opt-in to an attempt at cleaning up the correct cache.

Alternatively, if you know the name of your old precache, you can explicitly call caches.delete('old-precache-name') inside of an activate handler instead.

We are looking for feedback about how workbox.precaching.cleanupOutdatedCaches(), as a future release might default to enabling it instead of requiring developers to opt-in to using it.

Removal of workbox.precaching.supressWarnings()

A call to this method was generated by the build tools to turn off some warning messages that might otherwise be logged. This proved unnecessary, and for simplicity's sake, workbox.precaching.supressWarnings() has been removed from Workbox.

Other breaking changes:

  • Workbox log levels have been removed since now all developer tools support filtering visible logs by level. As a result, workbox.core.setLogLevel(), workbox.core.logLevel, and workbox.core.LOG_LEVELS have all been removed.

  • Workbox previously allowed developers to use workbox-strategies in one of two ways: by calling a workbox.strategies.strategyName() factory method, or by explicitly constructing new workbox.strategies.StrategyName(). To avoid confusion, the workbox.strategies.strategyName() approach is deprecated, and will be removed in v5. We encourage all developers to move to the new workbox.strategies.StrategyName() syntax. (#1842)

  • Various public interfaces and options have been renamed to standardize on capitalization. Most noticeably, 'Url' is now 'URL', 'Sw' is now 'SW', and the various strategyName handler values in runtimeCaching are now StrategyName (e.g. 'cacheFirst' is now 'CacheFirst'). The previous capitalization will remain supported until Workbox v5, but using the old variation will lead to deprecation warnings. All developers are encouraged to update their configuration to match the new, consistent capitalization. (#1833 and #1841)

  • workbox.skipWaiting() has been renamed to workbox.core.skipWaiting(), and workbox.clientsClaim() has been renamed to workbox.core.clientsClaim(). If you are using the skipWaiting or clientsClaim build configuration options, the new method names will be used in your generated service worker automatically.

🐛 What's Fixed?

  • Using fetchOptions to customize the behavior of a network request (e.g., by adding in an extra header) will now work when the request has a mode of 'navigate'. (#1825)

Thanks!

Special thanks to @tanhauhau for contributions that went into this release.

Workbox v4.0.0-beta.0

07 Nov 01:07
Compare
Choose a tag to compare
Workbox v4.0.0-beta.0 Pre-release
Pre-release

The first beta release of Workbox v4 includes the following developer-visible changes from the previous alpha release.

🎉 What's New?

  • [BREAKING CHANGE] The workbox.backgroundSync.Queue class has been updated to give developers much control over how failed requests are replayed when a sync event occurs. Previously, developers could only add requests to the queue (there was no option to remove them). Now they have low-level methods to push, pop, shift, and unshift requests. For the full list of changes and use cases, see #1710.

  • [BREAKING CHANGE] workbox-precaching will default to confirming that all Responses cached during installation have a non-error (less than 400) HTTP status code. If any Responses have an error code, the install phase will now fail. (The next time the service worker starts up, installation will be re-attempted.) Developers who need to precache Responses that have a 4xx or 5xx status code (e.g., precaching a /not-found.html URL that is served with a status code of 404) can opt-in to allowing that by passing in a custom cacheWillUpdate plugin to the workbox.precaching.PrecacheController's install method.

  • [BREAKING CHANGE] workbox-range-requests will now check to see if the Response object it's processing already has an HTTP status code of 206 (indicating that it contains partial content). If so, it will just pass it through unmodified. (#1721)

  • workbox.routing.Router now includes a routes getter method, giving developers access to the underlying Map of routes that have been registered for a given router. (#1714)

  • Improved logging when using workbox.routing.NavigationRoute. When a URL matches the blacklist, there's now a message logged with higher priority when using the development builds. (#1741)

  • When using workbox-precaching, the temporary cache is now cleaned up following service worker activation. (#1736)

Workbox v3.6.3

22 Oct 14:20
Compare
Choose a tag to compare

🐛 What's Fixed?

This release fixes an issue (#1677) that several users have reported, triggered by precaching a URL that returns a 30x redirect to another URL. For instance, having '/index.html' listed in your precache manifest can trigger this issue, if your web server responds to requests for '/index.html' with a 301 redirect to the destination URL '/'. When the issue manifests itself, the final, redirect content ends up being served with an incorrect Content-Type: response header, which can in turn lead problems displaying that cached content.

If you do use 30x redirects for some of your URLs, we recommend updating to this latest release of Workbox.

In order to "clear out" the problematic content that was previously precached with an incorrect Content-Type, after updating Workbox, you can deploy a small change to URLs that you know are affected (i.e. make any change to your '/index.html' file, if that's being fulfilled with a 30x redirect).

It's also possible to force all previously cached entries to be precached again by changing the cacheId option in "generate SW" mode, or by including

workbox.core.setCacheNameDetails({precache: 'my-new-id'});

in your service worker source file in "inject manifest" mode.

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/

Workbox v4.0.0-alpha.0

11 Oct 00:22
Compare
Choose a tag to compare
Pre-release

Overview of Workbox v4

We're happy to announce the first alpha release of Workbox's v4! This release brings a relatively small number of breaking changes, and we anticipate a straightforward migration for most developers. Here's what to watch out for:

🎉 What's New?

workbox-routing logic can now be used outside of a fetch event

Most of the time a workbox router instance is responding to a fetch event by matching that event's request against the list of registered routes. But there are some cases where you want to reuse your existing routing and caching strategy logic outside of receiving fetch events. The two most common use cases are:

  • Caching URLs that were fetched prior to the service worker controlling the page.
  • Pre-caching URLs that you think the user will likely need in the near future.

The Router class's handleRequest() method now takes an object in the form of {request, [event]} (where event is optional). When called, the router will then make and cache the request according to whatever caching strategies/plugins are used by the matching route.

Note: the use cases described above are different from pre-caching via workbox-precaching in that they're resources that can best be determined at runtime. workbox-precaching, on the other hand, should be used for caching resources that can best be determined at build time.

See #1682 for details.

workbox-broadcast-cache-update no longer requires the Broadcast Channel API and defers notifications on navigation requests

The workbox-broadcast-cache-update library would previously only work in browsers that supported the Broadcast Channel API. Nothing would happen when it was used in browsers that lacked support.

Starting in v4, the code will automatically fall back to iterating over all the open window clients and sending them an update message, one by one, using the postMessage() API.

In addition, when the workbox-broadcast-cache-update plugin would detect updates for navigation requests, most of the time the page the user is navigating to will not be ready to receive the update notification at the time when it's sent. To help deal with this issue, the plugin now defers notifications on navigation requests until a configurable timeout has passed, or until it receives a ready signal from the window.

See #1673 for details.

MIT Licensing

Workbox has moved from using the Apache 2 license to the MIT license. The motivation is similar to what led Angular to previously make the same switch.

⚠️ Breaking Changes

Modern transpilation targets

Workbox uses the (excellent) Babel project, along with @babel/preset-env, to transpile our source code to various runtime targets.

For Workbox libraries that run in a node environment (e.g. workbox-build, workbox-cli, and workbox-webpack-plugin), we've updated the transpilation target to node version 6. This means we've dropped compatibility with node version 4, which has reached its official end-of-life date. (#1654)

For Workbox libraries that run in the service worker environment (e.g. workbox-sw, and all the other runtime code), we've updated the transpilation target to Chrome 56. We chose this target because it matches the capabilities of Samsung Internet v6 and higher. This means we've dropped compatibility with any browser based on Chrome versions earlier than 56, like Samsung Internet v5. (#1655)

Our intention is to be fully compatible with all "evergreen" browsers, including Chrome, Firefox, Edge, or Safari.

Standard failure behavior for the various workbox-strategies

Previously, the various workbox-strategies would behave differently in failure scenarios. Some, like networkFirst, would resolve with an undefined value when there was a network failure and a cache miss. Other strategies would reject with a NetworkError under a similar failure.

Starting in v4, we've standardized how all of the workbox-strategies behave when they can't return a response due to some combination of network failure and/or cache miss: the promise than they return will consistently reject with a WorkboxError. This makes it much easier to think about handling failures with "fallback content," making patterns using custom handlers like the following work consistently, regardless of the strategy being used. (#1657)

workbox.routing.registerRoute(
  new RegExp('/some/path/prefix'),
  async ({event}) => {
    try {
      return await workbox.strategies.networkFirst().handle({event});
    } catch (error) {
      return caches.match(FALLBACK_URL);
    }
  }
);

workbox-webpack-plugin will now precache manifest.json by default

Previously, the default configuration would cause workbox-webpack-plugin to exclude files named manfiest.json from the list of files to precache. Because some browsers do in fact make use of the service worker cache when reading the web app manifest data, it makes more sense to default to including, rather than excluding, that file. (#1679)

🐛 What's Fixed?

Windows command line compatibility

As a byproduct of updating our projects various npm dependencies to the latest releases, we've fixed and issue that preventing the workbox-cli's wizard command from properly completing when run on a Windows command line environment. (#1658)

Precaching of HTTP 30x redirects

A bug in workbox-precaching previously could have caused URLs that lead to a HTTP 30x redirect to be cached incorrectly. This is now fixed. (#1678)

Failed service worker installations due to workbox-google-analytics

Certain content blocking browser extensions automatically cause calls like importScripts('/path/to/workbox-google-analyics.prod.js)to fail. That failure, in turn, will prevent a service worker from ever successfully installing. To prevent this trickle-down failure scenario, we've renamed the workbox-google-analytics.prod.js and workbox-google-analytics.dev.js to workbox-offline-ga.prod.js and workbox-offline-ga.dev.js.

This renaming does not impact whether or not client pages actually communicate with Google Analytics; it's done to make it more likely that the service worker's installation can complete. (#1688)

Workbox v3.6.2

28 Sep 15:04
Compare
Choose a tag to compare

🎉 What's New?

This release contains a fix for a missing dependency entry in workbox-webpack-plugin's package.json. Thanks to @arcanis for contributing the fix in #1667!

There are no functional changes in this release.

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/

Workbox v3.6.1

19 Sep 22:22
Compare
Choose a tag to compare

🎉 What's New?

Added the disable() method to workbox.navigationPreload

  • workbox.navigationPreload provides an enable() method to enable navigation preload, but it did not provide a way to disable it (without invoking the underlying service worker APIs). Now developers can call workbox.navigationPreload.disable() to disable navigation preload. (#1651)

The method option can now be used for runtime caching via generateSW()

  • Incorrect validation logic was preventing the method option from being used by runtime caching configuration in generateSW(). Thanks to @chrisdns, this has been fixed! (#1638)

Bug fixes and ergonomic improvements

  • Using workbox.expiration.Plugin with purgeOnQuotaError set to true would result in an error. Thanks to @salmoro for discovering and fixing the issue! (#1643).
  • Plugin lifecycle callbacks previously were not called with the event that triggered them, so developers writing custom plugins could not access any information about the event in those callback. Now all plugin callback are passed the event object (when available). (#1640)
  • The workbox-streams package's strategy() method is exposed on the browser build of workbox.streams that gets loaded by the workbox-sw loader, but it wasn't exported by the module in a way that was accessible to module bundlers. Now it's possible to import {strategy} from workbox-streams/strategy.mjs. (#1635).

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/

Workbox v3.5.0

11 Sep 15:21
Compare
Choose a tag to compare

🎉 What's New?

More customization when generating a service worker

Developers who use Workbox to generate their service worker (using the CLI, Node interface, or webpack plugin) can now take advantage of some additional options:

  • Setting offlineGoogleAnalytics: true will automatically add code to initialize Workbox's offline Google Analytics support in the generated service worker.

  • Both fetchOptions and matchOptions can now be used when configuring a runtimeCaching route, and those values will be passed through when constructing the corresponding Workbox caching strategy. Many thanks to @peterjosling for contributing this in #1608.

  • Using a custom plugin within a runtimeCaching route is now possible, thanks to enhancements made by @tsirlucas in #1598.

Here's a snippet of Workbox's build configuration, showing off all of the new features:

{
  // ... other options ...
  offlineGoogleAnalytics: true,
  runtimeCaching: {[
    urlPattern: /abc/,
    handler: 'staleWhileRevalidate',
    options: {
      fetchOptions: {
        mode: 'no-cors',
      },
      matchOptions: {
        ignoreSearch: true,
      },
      plugins: [{
        cacheDidUpdate: async ({cacheName, request, oldResponse, newResponse}) => {
          // Do something in your custom plugin.
        },
      }],
    },
  ]},
}

Support for the PATCH method in Workbox's router

Developers who need to match HTTP PATCH requests using Workbox's router can now do so, thanks to @kevin-brotcke's change in #1618.

Note that non-GET requests can't be added to a cache, so this is most useful when used alongside a network-only strategy configured with the Workbox background sync plugin, in order to retry failed PATCH requests once the network becomes available.

workbox.core.registerQuotaErrorCallback is now publicly visible

Due to a scoping error, the workbox.core.registerQuotaErrorCallback() function was previously not exposed. This is now public, matching the documented interface. Thanks to @Tronil for pointing out this discrepancy in #1616.

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/

Workbox v3.4.1

12 Jul 17:05
Compare
Choose a tag to compare

🎉 What's New?

Support for navigation preload

The new workbox-navigation-preload module provides a simple way of opting-in to navigation preload on browsers that support the feature. When run on browsers which lack navigation preload support, using the module will have no effect.

To take advantage of this new feature, you should make sure to set up a route that will match navigation requests, and uses a strategy that makes use of the response from the network, like networkFirst, staleWhileRevalidate, networkOnly, or cacheFirst.

// Enable navigation preloads.
workbox.navigationPreload.enable();

// Swap in networkOnly, cacheFirst, or staleWhileRevalidate as needed.
const strategy = workbox.strategies.networkFirst({
  cacheName: 'cached-navigations',
  plugins: [
    // Any plugins, like workbox.expiration, etc.
  ],
});

const navigationRoute = new workbox.routing.NavigationRoute(strategy, {
  // Optionally, provide a white/blacklist of RegExps to determine
  // which paths will match this route.
  // whitelist: [],
  // blacklist: [],
});

workbox.routing.registerRoute(navigationRoute);

Developers who are already handling navigations by responding with precached HTML (potentially configured with an App Shell fallback) do not need to enable navigation preload! This feature is intended to reduce navigation latency for developers who can't precache their HTML, but still want to use Workbox to handle caching of other assets on their sites.

workbox.strategies now supports using custom CacheQueryOptions

Developers who want to customize how workbox.strategies performs its internal cache lookups can now pass in a matchOptions parameter to use as the CacheQueryOptions when cache.match() is called under the hood.

// Ignore all query parameters when performing cache lookups.
const strategy = workbox.strategies.staleWhileRevalidate({
  cacheName: 'runtime-cache',
  matchOptions: {
    ignoreSearch: true,
  },
});

Many thanks to @torbs for contributing this in #1561!

🐛 What's Fixed?

  • A fix for an issue that could prevent workbox.expiration.Plugin from working as intended in Microsoft Edge. Thanks to @josephliccini for contributing #1510!

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/

Workbox v3.3.1

27 Jun 17:58
Compare
Choose a tag to compare

🐛 What's Fixed?

  • Don't alias the exported workbox.core.registerQuotaExceededCallback symbol [#1553] (Thanks to @xe21500 and others for reporting)
  • Properly set Cache-Control on CDN hosting [#1539]
  • Link to workbox.setConfig() docs after calling workbox copyLibraries [#1553]

📖 Learn More

Check out our docs @ developers.google.com/web/tools/workbox/