Workbox v4.0.0
Overview of Workbox v4
We're happy to announce the release of Workbox version 4! This release introduces a lot of great new features, as well as some breaking changes.
You can read the full list of changes here; we've also published a guide on migrating from v3 to v4.
🎉 What's New?
workbox-window
The workbox-window package is a set of modules that are intended to run in the window context, which is to say, inside of your web pages. They're a complement to the other workbox packages that run in the service worker.
The key features/goals of workbox-window are:
- To simplify the process of service worker registration and updates by helping developers identify the most critical moments in the service worker lifecycle, and making it easier to respond to those moments.
- To help prevent developers from making the most common mistakes.
- To enable easier communication between code running in the service worker and code running in the window.
You can use workbox-window by importing it into your code from our CDN as show in the following example:
<script type="module">
import {Workbox} from 'https://storage.googleapis.com/workbox-cdn/releases/4.0.0/workbox-window.prod.mjs';
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
wb.register();
}
</script>To learn more, see the workbox-window usage guide or the Workbox class reference documentation.
workbox-routing
-
Logging has improved for
workbox.routing.NavigationRoutewhen a URL matches the blacklist. Now a message with higher priority is logged when using the development builds. [#1741] -
workbox.routing.Routernow includes aroutesgetter method, giving developers access to the underlyingMapof routes that have been registered for a given router. [#1714] -
The
Router#handleRequest()method no longer requires aneventbe passed, which allows routing logic to be used programmatically, outside of the context of afetchevent. This can be useful as a way to cache URLs using the same strategies and plugins that you've already defined in your routing logic. [#1682]
workbox-google-analytics
- If you use Google Tag Manager (GTM) to load Google Analytics on your site, Workbox will now cache the
gtm.jslibrary so it will work offline as well [#1869].
workbox-broadcast-update
- The
workbox-broadcast-updateplugin now works in browsers that don't support theBroadcastChannelAPI by iterating over all the open window clients and sending them the update message viapostMessage()API. In addition, thechannelparameter is no longer required. If no channel is given the default channel nameworkboxis used (no channle is used for browsers that don't support theBroadcastChannelAPI). [#1673]
Build tools
- Support for a new
booleanconfiguration option,cleanupOutdatedCaches, has been added to theGenerateSWmode of all of the build tools. It defaults tofalse. When set totrue, a call toworkbox.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]
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.
🐛 What's Fixed?
workbox-precaching
- A bug in
workbox-precachingpreviously could have caused URLs that lead to a HTTP 30x redirect to be cached incorrectly. This is now fixed. [#1678]
workbox-expiration
- The
workbox-expirationdocumentation states that themaxAgeSecondsoption will expire entires based on the time they were last accessed. But due to a bug in the logic, it would actually expire entries based on the time they were originally cached. This has been fixed, and the behavior now matches the documentation [#1883].
workbox-strategies
- The default check for whether a response is cacheable now looks explicitly for a status code of
200, rather than checking forresponse.ok(which is true for any status code in the range200-209). In practice, this means that partial responses with a status code of206won't be inadvertently cached by default. [#1805]
workbox-webpack-plugin
- In addition to
swSrcbeing a file on the 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 toinject-manifestplugin. [#1763]
workbox-core
-
To work around an issue that could lead to failed navigations,
fetchOptionsare no longer set whenrequest.modeis 'navigate'. [#1862] -
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]
Build tools
-
The default
injectionPointRegexpoption value has been updated to exclude a leading.character, making it friendlier to developers who are bundling their own service worker files. [#1834] -
Support has been added for including JavaScript functions when configuring
runtimeCachingin the various build tools. [#1770, #1778] -
workbox-clinow supports a--watchparameter. When used, it will re-run the service worker build whenever any of the files in the precache manifest change. [#1776] -
The
workbox-webpack-pluginwill append to, rather than overwrite, any existingself.__precacheManifestvalue, making it easier to combine a precache manifest with the manifest generated by the plugin. [#1775] -
As a byproduct of updating our projects various
npmdependencies to the latest releases, we've fixed and issue that preventing theworkbox-cli'swizardcommand from properly completing when run on a Windows command line environment. [#1658]
workbox-google-analytics
-
Some content blocking browser extensions would block requests for script files containing the substring
analytics. When these requests are blocked, and error is thrown which causes the service worker installation to fail. To prevent this failure from affecting all service worker functionality, we've renamed theworkbox-google-analytics.prod.jsandworkbox-google-analytics.dev.jstoworkbox-offline-ga.prod.jsandworkbox-offline-ga.dev.js. [#1688]Note: This change is not an attempt to get around content blockers preventing Google Analytics tracking, as requests to all Google Analytics endponts will still be blocked. This change is just to prevent the entire service worker from breaking.
⚠️ Breaking Changes
Global changes
-
Various public interfaces and options have been renamed to standardize on capitalization. Most noticeably,
'Url'is now 'URL','Sw' is now'SW', and the variousstrategyNamehandler values inruntimeCachingare nowStrategyName(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, #1841] -
The npm names of the following two packages has change to reflect their browser namespace:
workbox-cache-expiration➡️workbox-expirationworkbox-broadcast-cache-update➡️workbox-broadcast-update
This change only affects developers who bundle their service worker from npm dependencies. Developers who load Workbox using
workbox-swshould not have to change their code. [#1879] -
Our
@babel/preset-envtranspilation targets have been updated to>= node 6for node libraries and>= Chrome 56for service worker libraries. Note: we chose Chrome 56 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]
workbox-core
- 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, andworkbox.core.LOG_LEVELShave all been removed. [#1831]
workbox-strategies
-
Workbox previously allowed developers to use
workbox-strategiesin one of two ways: by calling aworkbox.strategies.strategyName()factory method, or by explicitly constructingnew workbox.strategies.StrategyName(). To avoid confusion, theworkbox.strategies.strategyName()approach is deprecated, and will be removed in v5. We encourage all developers to move to thenew workbox.strategies.StrategyName()syntax. [#1831, #1842] -
Previously, the various
workbox-strategieswould behave differently in failure scenarios. Some, likenetworkFirst, would resolve with anundefinedvalue when there was a network failure and a cache miss. Other strategies would reject with aNetworkErrorunder a similar failure. Starting in v4, we've standardized how all of theworkbox-strategiesbehave when they can't return a response due to some combination of network failure and/or cache miss: the promise that they return will consistently reject with aWorkboxError. 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-precaching
-
workbox-precachingwill default to confirming that allResponses cached during installation have a non-error (less than400) HTTP status code. If anyResponses have an error code, theinstallphase will now fail. (The next time the service worker starts up, installation will be re-attempted.) Developers who need to precacheResponses that have a 4xx or 5xx status code (e.g., precaching a/not-found.htmlURL that is served with a status code of404) can opt-in to allowing that by passing in a customcacheWillUpdateplugin to theworkbox.precaching.PrecacheController'sinstallmethod. -
workbox-precachinghas 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. There is more information in our migration guide detailing specific changes you might need to make to account for the new precaching behavior.
workbox-sw
workbox.skipWaiting()has been renamed toworkbox.core.skipWaiting(), andworkbox.clientsClaim()has been renamed toworkbox.core.clientsClaim(). If you are using theskipWaitingorclientsClaimbuild configuration options, the new method names will be used in your generated service worker automatically.
workbox-expiration
- The underlying IndexedDB data model for cached entry metadata has changed from using IndexedDB database names that match the cache name (one database per cache name) to a single database named
workbox-expiration. If you had code that was manually inspected this metadata, you'll need to update it to check the new database [#1883].
workbox-background-sync
- The
workbox.backgroundSync.Queueclass has been updated to give developers more control over how failed requests are replayed when asyncevent 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.
workbox-range-requests
workbox-range-requestswill now check to see if theResponseobject 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-webpack-plugin
workbox-webpack-pluginwill now precachemanifest.jsonby default. Previously, the default configuration would causeworkbox-webpack-pluginto exclude files namedmanfiest.jsonfrom 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]
Thanks!
Special thanks to @tanhauhau, @xMokAx, and @tomayac for contributions that went into this release, and to @webmaxru and @jadjoubran for help testing all the pre-releases!