Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 966361 of CacheStorage

  • Revision slug: Web/API/CacheStorage
  • Revision title: CacheStorage
  • Revision id: 966361
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

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

The CacheStorage interface of the ServiceWorker API represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.

CacheStorage also exposes {{domxref("CacheStorage.open()")}} and {{domxref("CacheStorage.match()")}}. 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("WorkerGlobalScope.caches", "caches")}} property.

Note: The CacheStorage interface is exposed to windowed scopes as well as workers; you don't have to use it in conjunction with service workers.
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 opening your cache with {{domxref("CacheStorage.open()")}}, returning the entries it contains with {{domxref("CacheStorage.keys()")}}, and matching the one you want with {{domxref("CacheStorage.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 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 returns 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. 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()).)
  3. If this fails (e.g. because the network is down), return a fallback response.

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

this.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/',
        '/sw-test/gallery/bountyHunters.jpg',
        '/sw-test/gallery/myLittleVader.jpg',
        '/sw-test/gallery/snowTroopers.jpg'
      ]);
    })
  );
});

this.addEventListener('fetch', function(event) {
  var cachedResponse = caches.match(event.request).catch(function() {
    return fetch(event.request).then(function(response) {
      return caches.open('v1').then(function(cache) {
        cache.put(event.request, response.clone());
        return response;
      });  
    });
  }).catch(function() {
    return caches.match('/sw-test/gallery/myLittleVader.jpg');
  });
    
  event.respondWith(cachedResponse);
});

Specifications

Specification Status Comment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}} {{Spec2('Service Workers')}} Initial definition.

Browser compatibility

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome(40.0)}} {{CompatGeckoDesktop(39)}} {{CompatNo}} {{CompatUnknown}} {{CompatNo}}
Accessible from {{domxref("Window")}} {{CompatChrome(43.0)}} {{CompatGeckoDesktop(39)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Accessible from {{domxref("WorkerGlobalScope")}} {{CompatChrome(43.0)}} {{CompatGeckoDesktop(39)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile(39)}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatChrome(40.0)}}
Accessible from {{domxref("Window")}} {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile(39)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatChrome(43.0)}}
Accessible from {{domxref("WorkerGlobalScope")}} {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile(39)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatChrome(43.0)}}

See also

Revision Source

<p>{{APIRef("Service Workers API")}}{{SeeCompatTable}}</p>

<p>The <strong><code>CacheStorage</code></strong> interface of the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}}&nbsp;can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.</p>

<p><code>CacheStorage</code> also exposes {{domxref("CacheStorage.open()")}}&nbsp;and {{domxref("CacheStorage.match()")}}. Use {{domxref("CacheStorage.open()")}}&nbsp;to obtain a {{domxref("Cache")}}&nbsp;instance. Use {{domxref("CacheStorage.match()")}}&nbsp;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("WorkerGlobalScope.caches", "caches")}} property.</p>

<div class="note"><strong>Note</strong>: The <code>CacheStorage</code> interface is exposed to windowed scopes as well as workers; you don't have to use it in conjunction with service workers.</div>

<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 opening your cache with {{domxref("CacheStorage.open()")}}, returning the entries it contains with {{domxref("CacheStorage.keys()")}}, and matching the one you want with {{domxref("CacheStorage.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 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 returns <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">
this.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/',
        '/sw-test/gallery/bountyHunters.jpg',
        '/sw-test/gallery/myLittleVader.jpg',
        '/sw-test/gallery/snowTroopers.jpg'
      ]);
    })
  );
});

this.addEventListener('fetch', function(event) {
  var cachedResponse = caches.match(event.request).catch(function() {
    return fetch(event.request).then(function(response) {
      return caches.open('v1').then(function(cache) {
        cache.put(event.request, response.clone());
        return response;
      });  
    });
  }).catch(function() {
    return caches.match('/sw-test/gallery/myLittleVader.jpg');
  });
    
  event.respondWith(cachedResponse);
});</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', '#cache-storage', 'CacheStorage')}}</td>
   <td>{{Spec2('Service Workers')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(40.0)}}</td>
   <td>{{CompatGeckoDesktop(39)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td>Accessible from {{domxref("Window")}}</td>
   <td>{{CompatChrome(43.0)}}</td>
   <td>{{CompatGeckoDesktop(39)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>Accessible from {{domxref("WorkerGlobalScope")}}</td>
   <td>{{CompatChrome(43.0)}}</td>
   <td>{{CompatGeckoDesktop(39)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile(39)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatChrome(40.0)}}</td>
  </tr>
  <tr>
   <td>Accessible from {{domxref("Window")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile(39)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(43.0)}}</td>
  </tr>
  <tr>
   <td>Accessible from {{domxref("WorkerGlobalScope")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile(39)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(43.0)}}</td>
  </tr>
 </tbody>
</table>
</div>

<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("WorkerGlobalScope.caches")}}</li>
</ul>
Revert to this revision