From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/es/web/api/cachestorage/index.html | 198 ++++++++++++++++++++++++++ files/es/web/api/cachestorage/keys/index.html | 74 ++++++++++ 2 files changed, 272 insertions(+) create mode 100644 files/es/web/api/cachestorage/index.html create mode 100644 files/es/web/api/cachestorage/keys/index.html (limited to 'files/es/web/api/cachestorage') diff --git a/files/es/web/api/cachestorage/index.html b/files/es/web/api/cachestorage/index.html new file mode 100644 index 0000000000..fdcfe56217 --- /dev/null +++ b/files/es/web/api/cachestorage/index.html @@ -0,0 +1,198 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +tags: + - API + - CacheStorage + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorker + - TopicStub +translation_of: Web/API/CacheStorage +--- +

{{APIRef("Service Workers API")}}

+ +

The CacheStorage interface represents the storage for {{domxref("Cache")}} objects.

+ +

The interface:

+ + + +

Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.

+ +

Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the CacheStorage object tracks.

+ +

You can access CacheStorage through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.

+ +
Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.
+ +
Note: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.
+ +

Methods

+ +
+
{{domxref("CacheStorage.match()")}}
+
Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.
+
{{domxref("CacheStorage.has()")}}
+
Returns a {{jsxref("Promise")}} that resolves to true if a {{domxref("Cache")}} object matching the cacheName exists.
+
{{domxref("CacheStorage.open()")}}
+
Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the cacheName (a new cache is created if it doesn't already exist.)
+
{{domxref("CacheStorage.delete()")}}
+
Finds the {{domxref("Cache")}} object matching the cacheName, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to true. If no {{domxref("Cache")}} object is found, it resolves to false.
+
{{domxref("CacheStorage.keys()")}}
+
Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.
+
+ +

Examples

+ +

This code snippet is from the MDN sw-test example (see sw-test running live.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.

+ +

In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:

+ +
    +
  1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
  2. +
  3. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (cache.put(event.request, response.clone()).)
  4. +
  5. If this fails (e.g. because the network is down), return a fallback response.
  6. +
+ +

Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.

+ +
self.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  event.respondWith(caches.match(event.request).then(function(response) {
+    // caches.match() always resolves
+    // but in case of success response will have value
+    if (response !== undefined) {
+      return response;
+    } else {
+      return fetch(event.request).then(function (response) {
+        // response may be used only once
+        // we need to save clone to put one copy in cache
+        // and serve second one
+        let responseClone = response.clone();
+
+        caches.open('v1').then(function (cache) {
+          cache.put(event.request, responseClone);
+        });
+        return response;
+      }).catch(function () {
+        return caches.match('/sw-test/gallery/myLittleVader.jpg');
+      });
+    }
+  }));
+});
+
+ +

This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code.

+ +
// Try to get data from the cache, but fall back to fetching it live.
+async function getData() {
+   const cacheVersion = 1;
+   const cacheName    = `myapp-${ cacheVersion }`;
+   const url          = 'https://jsonplaceholder.typicode.com/todos/1';
+   let cachedData     = await getCachedData( cacheName, url );
+
+   if ( cachedData ) {
+      console.log( 'Retrieved cached data' );
+      return cachedData;
+   }
+
+   console.log( 'Fetching fresh data' );
+
+   const cacheStorage = await caches.open( cacheName );
+   await cacheStorage.add( url );
+   cachedData = await getCachedData( cacheName, url );
+   await deleteOldCaches( cacheName );
+
+   return cachedData;
+}
+
+// Get data from the cache.
+async function getCachedData( cacheName, url ) {
+   const cacheStorage   = await caches.open( cacheName );
+   const cachedResponse = await cacheStorage.match( url );
+
+   if ( ! cachedResponse || ! cachedResponse.ok ) {
+      return false;
+   }
+
+   return await cachedResponse.json();
+}
+
+// Delete any old caches to respect user's disk space.
+async function deleteOldCaches( currentCache ) {
+   const keys = await caches.keys();
+
+   for ( const key of keys ) {
+      const isOurCache = 'myapp-' === key.substr( 0, 6 );
+
+      if ( currentCache === key || ! isOurCache ) {
+         continue;
+      }
+
+      caches.delete( key );
+   }
+}
+
+try {
+   const data = await getData();
+   console.log( { data } );
+} catch ( error ) {
+   console.error( { error } );
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cachestorage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.CacheStorage")}}

+ +

See also

+ + diff --git a/files/es/web/api/cachestorage/keys/index.html b/files/es/web/api/cachestorage/keys/index.html new file mode 100644 index 0000000000..eee8e0e443 --- /dev/null +++ b/files/es/web/api/cachestorage/keys/index.html @@ -0,0 +1,74 @@ +--- +title: CacheStorage.keys() +slug: Web/API/CacheStorage/keys +translation_of: Web/API/CacheStorage/keys +--- +

{{APIRef ("API de Service Workers")}}

+ +

El keys()método de la interfaz {{domxref ("CacheStorage")}} devuelve un {{jsxref ("Promise")}} que se resolverá con una matriz que contiene las cadenas correspondientes a todos los {{domxref ("Cache")}} objetos rastreados por el objeto {{domxref ("CacheStorage")}} en el orden en que fueron creados. Use este método para iterar sobre una lista de todos los objetos {{domxref ("Cache")}}.

+ +

Puede acceder a CacheStoragetravés de la propiedad global {{domxref ("WindowOrWorkerGlobalScope.caches", "caches")}}.

+ +

Sintaxis

+ +
caches.keys().then(function(keyList) {
+  // haz algo con tu keyList
+});
+
+ +

Parámetros

+ +

Ninguna.

+ +

Valor de retorno

+ +

a {{jsxref("Promise")}} that resolves with an array of the {{domxref("Cache")}} names inside the {{domxref("CacheStorage")}} object.

+ +

Examples

+ +

In this code snippet we wait for an {{domxref("ServiceWorkerGlobalScope.onactivate", "activate")}} event, and then run a {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} block that clears up any old, unused caches before a new service worker is activated. Here we have a whitelist containing the names of the caches we want to keep (cacheWhitelist). We return the keys of the caches in the {{domxref("CacheStorage")}} object using keys(), then check each key to see if it is in the whitelist. If not, we delete it using {{domxref("CacheStorage.delete()")}}.

+ +
then.addEventListener('activar', función (evento) { 
+  var cacheWhitelist = ['v2']; 
+
+  event.waitUntil( 
+    caches.keys().then(function(keyList) { 
+      return Promise.all(keyList.map(function(key) {
+        if (cacheWhitelist.indexOf(key) === -1) {
+          return caches.delete(key);
+        }
+      });
+    })
+  );
+});
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Service Workers', '# dom-cachestorage-keys', 'CacheStorage: keys')}}{{Spec2 ('Trabajadores de servicio')}}Definición inicial
+ +

Compatibilidad del navegador

+ + + +

{{Compat("api.CacheStorage.keys")}}

+ +

Ver también

+ + -- cgit v1.2.3-54-g00ecf