Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
sw-toolbox
Advanced tools
> A collection of tools for [service workers](https://slightlyoff.github.io/ServiceWorker/spec/service_worker/)
A collection of tools for service workers
Service Worker Toolbox provides some simple helpers for use in creating your own service workers. If you're not sure what service workers are or what they are for, start with the explainer doc.
Service Worker Toolbox is available through Bower, npm or direct from github:
bower install --save sw-toolbox
npm install --save sw-toolbox
git clone https://github.com/GoogleChrome/sw-toolbox.git
From your registering page, register your service worker in the normal way. For example:
navigator.serviceWorker.register('my-service-worker.js');
For even lower friction, if you don't intend to doing anything more fancy than just registering with a default scope, you can instead include the Service Worker Toolbox companion script in your HTML:
<script src="/path/to/sw-toolbox/companion.js" data-service-worker="my-service-worker.js"></script>
As currently implemented in Chrome 40+, a service worker must exist at the root of the scope that you intend it to control, or higher. So if you want all of the pages under /myapp/
to be controlled by the worker, the worker script itself must be served from either /
or /myapp/
. The default scope is the containing path of the service worker script.
In your service worker you just need to use importScripts
to load Service Worker Toolbox
importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup
Within your service worker file
// Set up routes from URL patterns to request handlers
toolbox.router.get('/myapp/index.html', someHandler);
// For some common cases Service Worker Toolbox provides a built-in handler
toolbox.router.get('/', toolbox.networkFirst);
// URL patterns are the same syntax as ExpressJS routes
// (http://expressjs.com/guide/routing.html)
toolbox.router.get(':foo/index.html', function(request, values) {
return new Response('Handled a request for ' + request.url +
', where foo is "' + values.foo + '"');
});
// For requests to other origins, specify the origin as an option
toolbox.router.post('/(.*)', apiHandler, {origin: 'https://api.example.com'});
// Provide a default handler for GET requests
toolbox.router.default = myDefaultRequestHandler;
// You can provide a list of resources which will be cached at service worker install time
toolbox.precache(['/index.html', '/site.css', '/images/logo.png']);
A request handler receives three arguments
var myHandler = function(request, values, options) {
// ...
}
request
- Request object that triggered the fetch
eventvalues
- Object whose keys are the placeholder names in the URL pattern, with the values being the corresponding part of the request URL. For example, with a URL pattern of '/images/:size/:name.jpg'
and an actual URL of '/images/large/unicorns.jpg'
, values
would be {size: 'large', name: 'unicorns'}
options
- the options object that was used when creating the routeThe return value should be a Response, or a Promise that resolves with a Response. If another value is returned, or if the returned Promise is rejected, the Request will fail which will appear to be a NetworkError to the page that made the request.
There are 5 built-in handlers to cover the most common network strategies. For more information about offline strategies see the Offline Cookbook.
toolbox.networkFirst
Try to handle the request by fetching from the network. If it succeeds, store the response in the cache. Otherwise, try to fulfill the request from the cache. This is the strategy to use for basic read-through caching. Also good for API requests where you always want the freshest data when it is available but would rather have stale data than no data.
toolbox.cacheFirst
If the request matches a cache entry, respond with that. Otherwise try to fetch the resource from the network. If the network request succeeds, update the cache. Good for resources that don't change, or for which you have some other update mechanism.
toolbox.fastest
Request the resource from both the cache and the network in parallel. Respond with whichever returns first. Usually this will be the cached version, if there is one. On the one hand this strategy will always make a network request, even if the resource is cached. On the other hand, if/when the network request completes the cache is updated, so that future cache reads will be more up-to-date.
toolbox.cacheOnly
Resolve the request from the cache, or fail. Good for when you need to guarantee that no network request will be made - to save battery on mobile, for example.
toolbox.networkOnly
Handle the request by trying to fetch the URL from the network. If the fetch fails, fail the request. Essentially the same as not creating a route for the URL at all.
Any method that accepts an options
object will accept a boolean option of debug
. When true this causes Service Worker Toolbox to output verbose log messages to the worker's console.
Most methods that involve a cache (toolbox.cache
, toolbox.uncache
, toolbox.fastest
, toolbox.cacheFirst
, toolbox.cacheOnly
, toolbox.networkFirst
) accept an option called cacheName
, which is the name of the Cache that should be used. If not specified, Service Worker Toolbox will use a default cache.
The networkFirst
strategy supports a timeout, specified in seconds via the networkTimeoutSeconds
global or local option. If networkTimeoutSeconds
is explicitly set, then any network requests that
take longer than that amount of time will automatically fall back to the cached response if one
exists. By default, when networkTimeoutSeconds
is not set, the browser's native networking timeout
logic applies.
toolbox.router.get(urlPattern, handler, options)
toolbox.router.post(urlPattern, handler, options)
toolbox.router.put(urlPattern, handler, options)
toolbox.router.delete(urlPattern, handler, options)
toolbox.router.head(urlPattern, handler, options)
Create a route that causes requests for URLs matching urlPattern
to be resolved by calling handler
. Matches requests using the GET, POST, PUT, DELETE or HEAD HTTP methods respectively.
urlPattern
- an Express style route. See the docs for the path-to-regexp module for the full syntaxhandler
- a request handler, as described aboveoptions
- an object containing options for the route. This options object will be available to the request handler. The origin
option is specific to the route methods, and is an exact string or a Regexp against which the origin of the Request must match for the route to be used.toolbox.router.any(urlPattern, handler, options)
Like toolbox.router.get
, etc., but matches any HTTP method.
toolbox.router.default
If you set this property to a function it will be used as the request handler for any GET request that does not match a route.
toolbox.precache(arrayOfURLs)
Add each URL in arrayOfURLs to the list of resources that should be cached during the service worker install step. Note that this needs to be called before the install event is triggered, so you should do it on the first run of your script.
toolbox.cache(url, options)
Causes the resource at url
to be added to the cache. Returns a Promise. Supports the debug
and cache
global options.
toolbox.uncache(url, options)
Causes the resource at url
to be removed from the cache. Returns a Promise. Supports the debug
and cache
global options.
If you’ve found an error in this library, please file an issue: https://github.com/GoogleChrome/sw-toolbox/issues
Patches are encouraged, and may be submitted by forking this project and submitting a pull request through GitHub.
Copyright 2015 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
FAQs
Service Worker Toolbox provides some simple helpers for use in creating your own service workers.
The npm package sw-toolbox receives a total of 63,885 weekly downloads. As such, sw-toolbox popularity was classified as popular.
We found that sw-toolbox demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.