aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/api/cachestorage
diff options
context:
space:
mode:
Diffstat (limited to 'files/es/web/api/cachestorage')
-rw-r--r--files/es/web/api/cachestorage/index.html198
-rw-r--r--files/es/web/api/cachestorage/keys/index.html74
2 files changed, 272 insertions, 0 deletions
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
+---
+<p>{{APIRef("Service Workers API")}}</p>
+
+<p>The <strong><code>CacheStorage</code></strong> interface represents the storage for {{domxref("Cache")}} objects.</p>
+
+<p>The interface:</p>
+
+<ul>
+ <li>Provides a master directory of all the named caches that can be accessed by a {{domxref("ServiceWorker")}} or other type of worker or {{domxref("window")}} scope (you’re not limited to only using it with service workers, even though the {{SpecName('Service Workers')}} spec defines it).
+ <div class="note"><strong>Note</strong>: <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1026063">Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS</a>. {{domxref("window.caches")}} will be undefined unless an SSL certificate is configured.</div>
+ </li>
+ <li>Maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.</li>
+</ul>
+
+<p>Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.</p>
+
+<p>Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the <code>CacheStorage</code> object tracks.</p>
+
+<p>You can access <code>CacheStorage</code> through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.</p>
+
+<div class="note"><strong>Note</strong>: CacheStorage always rejects with a <code>SecurityError</code> 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.</div>
+
+<div class="note"><strong>Note</strong>: {{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()")}}.</div>
+
+<h2 id="Methods">Methods</h2>
+
+<dl>
+ <dt>{{domxref("CacheStorage.match()")}}</dt>
+ <dd>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.</dd>
+ <dt>{{domxref("CacheStorage.has()")}}</dt>
+ <dd>Returns a {{jsxref("Promise")}} that resolves to <code>true</code> if a {{domxref("Cache")}} object matching the <code>cacheName</code> exists.</dd>
+ <dt>{{domxref("CacheStorage.open()")}}</dt>
+ <dd>Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the <code>cacheName</code> (a new cache is created if it doesn't already exist.)</dd>
+ <dt>{{domxref("CacheStorage.delete()")}}</dt>
+ <dd>Finds the {{domxref("Cache")}} object matching the <code>cacheName</code>, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to <code>true</code>. If no {{domxref("Cache")}} object is found, it resolves to <code>false</code>.</dd>
+ <dt>{{domxref("CacheStorage.keys()")}}</dt>
+ <dd>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.</dd>
+</dl>
+
+<h2 id="Examples">Examples</h2>
+
+<p>This code snippet is from the MDN <a href="https://github.com/mdn/sw-test/">sw-test example</a> (see <a href="https://mdn.github.io/sw-test/">sw-test running live</a>.) 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.</p>
+
+<p>In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:</p>
+
+<ol>
+ <li>Check whether a match for the request is found in the CacheStorage. If so, serve that.</li>
+ <li>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")}} (<code>cache.put(event.request, response.clone())</code>.)</li>
+ <li>If this fails (e.g. because the network is down), return a fallback response.</li>
+</ol>
+
+<p>Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.</p>
+
+<pre class="brush: js notranslate">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');
+ });
+ }
+ }));
+});
+</pre>
+
+<p>This snippet shows how the API can be used outside of a service worker context, and uses the <code>await</code> operator for much more readable code.</p>
+
+<pre class="brush: js notranslate">// 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 } );
+}</pre>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('Service Workers', '#cachestorage', 'CacheStorage')}}</td>
+ <td>{{Spec2('Service Workers')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+
+
+<p>{{Compat("api.CacheStorage")}}</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li>
+ <li>{{domxref("Cache")}}</li>
+ <li>{{domxref("WindowOrWorkerGlobalScope.caches")}}</li>
+</ul>
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
+---
+<p><font><font>{{APIRef ("API de Service Workers")}}</font></font></p>
+
+<p><span class="seoSummary"><font><font>El </font></font><code><strong>keys</strong></code><strong><code>()</code></strong><font><font>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. </font><font>Use este método para iterar sobre una lista de todos los objetos {{domxref ("Cache")}}.</font></font></span></p>
+
+<p><font><font>Puede acceder a </font></font><code>CacheStorage</code><font><font>través de la propiedad global {{domxref ("WindowOrWorkerGlobalScope.caches", "caches")}}.</font></font></p>
+
+<h2 id="Sintaxis"><font><font>Sintaxis</font></font></h2>
+
+<pre class="syntaxbox notranslate"><font><font>caches.keys().then(function(</font></font><em><font><font>keyList</font></font></em><font><font>) {</font></font><font><font>
+ // haz algo con tu keyList</font></font><font><font>
+});</font></font>
+</pre>
+
+<h3 id="Parámetros"><font><font>Parámetros</font></font></h3>
+
+<p><font><font>Ninguna.</font></font></p>
+
+<h3 id="Valor_de_retorno"><font><font>Valor de retorno</font></font></h3>
+
+<p>a {{jsxref("Promise")}} that resolves with an array of the {{domxref("Cache")}} names inside the {{domxref("CacheStorage")}} object.</p>
+
+<h2 id="Examples" style="line-height: 30px; font-size: 2.14285714285714rem;">Examples</h2>
+
+<p>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 (<code>cacheWhitelist</code>). We return the keys of the caches in the {{domxref("CacheStorage")}} object using <code>keys()</code>, then check each key to see if it is in the whitelist. If not, we delete it using {{domxref("CacheStorage.delete()")}}.</p>
+
+<pre class="brush: js notranslate"><font><font><font><font>then.addEventListener('activar', función (evento) { </font></font></font></font><font><font><font><font>
+ var cacheWhitelist = ['v2']; </font></font></font></font>
+<font><font><font><font>
+ event.waitUntil( </font></font></font></font><font><font><font><font>
+ caches.keys().then(function(keyList) { </font></font></font></font><font><font><font><font>
+ return Promise.all(keyList.map(function(key) {</font></font></font></font><font><font>
+ if (cacheWhitelist.indexOf(key) === -1) {
+ return caches.delete(<font><font>key</font></font>);
+ }
+ });
+ })</font></font><font><font>
+ );</font></font><font><font>
+});</font></font></pre>
+
+<h2 id="Especificaciones"><font><font>Especificaciones</font></font></h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col"><font><font>Especificación</font></font></th>
+ <th scope="col"><font><font>Estado</font></font></th>
+ <th scope="col"><font><font>Comentario</font></font></th>
+ </tr>
+ <tr>
+ <td><font><font>{{SpecName('Service Workers', '# dom-cachestorage-keys', 'CacheStorage: keys')}}</font></font></td>
+ <td><font><font>{{Spec2 ('Trabajadores de servicio')}}</font></font></td>
+ <td><font><font>Definición inicial</font></font></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Compatibilidad_del_navegador"><font><font>Compatibilidad del navegador</font></font></h2>
+
+
+
+<p><font><font>{{Compat("api.CacheStorage.keys")}}</font></font></p>
+
+<h2 id="Ver_también"><font><font>Ver también</font></font></h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers"><font><font>Uso de trabajadores del servicio</font></font></a></li>
+ <li><font><font>{{domxref("Cache")}}</font></font></li>
+ <li><font><font><font><font>{{domxref("WindowOrWorkerGlobalScope.caches")}}</font></font></font></font></li>
+</ul>