This article is in need of a technical review.
This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.
The CacheStorage interface of the ServiceWorker API represents the storage for Cache objects. It provides a master directory of all the named caches that a ServiceWorker can access and maintains a mapping of string names to the corresponding Cache.
CacheStorage also exposes CacheStorage.open() and CacheStorage.match(). Use CashStorage.open() to obtain a Cache instance. Use CacheStorage.match() to check if a given Request is a key in any of the Cache objects that the CacheStorage object tracks.
CacheStorage interface is only exposed to Service Workers, not to other Web Workers or to windowed scopes.Methods
-
CacheStorage.match() -
Checks if a given
Requestis a key in any of theCacheobjects that theCacheStorageobject tracks and returns aPromisethat resolves to that match. -
CacheStorge.has() -
Returns a
Promisethat resolves totrueif aCacheobject matching thecacheNameexists. -
CacheStorage.open() -
Returns a
Promisethat resolves to theCacheobject matching thecacheName. -
CacheStorage.delete() -
Finds the
Cacheobject matching thecacheName, and if found, deletes theCacheobject and returns aPromisethat resolves totrue. If noCacheobject is found, it returnsfalse. -
CacheStorage.keys() -
Returns a
Promisethat will resolve with an array containing strings corresponding to all of the namedCacheobjects. Use this method to iterate over a list of all theCacheobjects tracked by theCacheStorage.
Examples
This code snippet is from the service worker post-message sample. The code uses the Window.postMessage() method to communicate with the service worker controlling the page. It uses CacheStorage.open() to open any Cache objects with a Content-Type header that start with post-message.
The code then uses a switch to maintain any Cache objects found: case 'keys' returns a list of the URLs corresponding to the Request objects that serve as keys for the current Cache. case 'add' adds a new Request/Response pair to the Cache. case 'delete' removes a Request/Response pair from the Cache (assuming it already exists).
The code also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple cashes. It maps a shorthand identifier for a cache to a specific, versioned cache name. The code also deletes all caches that aren't named in CURRENT_CACHES.
var CACHE_VERSION = 1;
var CURRENT_CACHES = {
'post-message': 'post-message-cache-v' + CACHE_VERSION
};
self.addEventListener('activate', function(event) {
var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
return CURRENT_CACHES[key];
});
// Active worker won't be treated as activated until promise resolves successfully.
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (expectedCacheNames.indexOf(cacheName) == -1) {
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('message', function(event) {
console.log('Handling message event:', event);
caches.open(CURRENT_CACHES['post-message']).then(function(cache) {
switch (event.data.command) {
// Returns list of URLs corresponding to Request objects
// that serve as keys for current cache.
case 'keys':
cache.keys().then(function(requests) {
var urls = requests.map(function(request) {
return request.url;
});
// event.ports[0] corresponds to the MessagePort that was transferred
// as part of the controlled page's call to controller.postMessage().
// Therefore, event.ports[0].postMessage() will trigger the onmessage
// handler from the controlled page.
event.ports[0].postMessage({
error: null,
urls: urls.sort()
});
});
break;
// Adds a new request/response pair to the cache.
case 'add':
var request = new Request(event.data.url, {mode: 'no-cors'});
cache.add(request).then(function() {
event.ports[0].postMessage({
error: null
});
});
break;
// Removes a request/response pair from the cache (assuming it exists).
case 'delete':
var request = new Request(event.data.url, {mode: 'no-cors'});
cache.delete(request).then(function(success) {
event.ports[0].postMessage({
error: success ? null : 'Item was not found in the cache.'
});
});
break;
default:
// This will be handled by the outer .catch().
throw 'Unknown command: ' + event.data.command;
}
}).catch(function(error) {
// If the promise rejects, return a standardized error message to the controlled page.
console.error('Message handling failed:', error);
event.ports[0].postMessage({
error: error.toString()
});
});
});
Specifications
| Specification | Status | Comment |
|---|---|---|
| Service Workers The definition of 'CacheStorage' in that specification. |
Working Draft | Initial definition. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 40.0 | ? | Not supported | ? | Not supported |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |