From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/cache/add/index.html | 198 ++++++++++++++++++ files/zh-cn/web/api/cache/addall/index.html | 202 ++++++++++++++++++ files/zh-cn/web/api/cache/delete/index.html | 150 ++++++++++++++ files/zh-cn/web/api/cache/index.html | 282 ++++++++++++++++++++++++++ files/zh-cn/web/api/cache/keys/index.html | 136 +++++++++++++ files/zh-cn/web/api/cache/match/index.html | 173 ++++++++++++++++ files/zh-cn/web/api/cache/matchall/index.html | 82 ++++++++ files/zh-cn/web/api/cache/put/index.html | 109 ++++++++++ 8 files changed, 1332 insertions(+) create mode 100644 files/zh-cn/web/api/cache/add/index.html create mode 100644 files/zh-cn/web/api/cache/addall/index.html create mode 100644 files/zh-cn/web/api/cache/delete/index.html create mode 100644 files/zh-cn/web/api/cache/index.html create mode 100644 files/zh-cn/web/api/cache/keys/index.html create mode 100644 files/zh-cn/web/api/cache/match/index.html create mode 100644 files/zh-cn/web/api/cache/matchall/index.html create mode 100644 files/zh-cn/web/api/cache/put/index.html (limited to 'files/zh-cn/web/api/cache') diff --git a/files/zh-cn/web/api/cache/add/index.html b/files/zh-cn/web/api/cache/add/index.html new file mode 100644 index 0000000000..dbce4c5b21 --- /dev/null +++ b/files/zh-cn/web/api/cache/add/index.html @@ -0,0 +1,198 @@ +--- +title: Cache.add() +slug: Web/API/Cache/add +translation_of: Web/API/Cache/add +--- +

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

+ +

{{domxref("Cache")}}接口的 add()方法接受一个URL作为参数,请求参数指定的URL,并将返回的response对象添加到给定的cache中。 add() 方法在功能上等同于以下代码:

+ +
fetch(url).then(function (response) {
+  if (!response.ok) {
+    throw new TypeError('bad response status');
+  }
+  return cache.put(url, response);
+})
+ +

对于更复杂的操作,您可以直接使用{{domxref("Cache.put","Cache.put()")}}这个API。

+ +
+

注意: add() 将会覆盖之前存储在cache中与request匹配的任何key/value对。

+
+ +
+

注意: 之前的Cache  (Blink 和 Gecko内核版本) 在实现{{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, 和 {{domxref("Cache.put")}} 的策略是在response结果完全写入缓存后才会resolve当前的promise。更新后的规范版本中一旦条目被记录到数据库就会resolve当前的promise,即使当前response结果还在传输中。

+
+ +

语法

+ +
cache.add(request).then(function() {
+  //request has been added to the cache
+});
+
+ +

参数

+ +
+
request
+
要添加到cache的request。它可以是一个 {{domxref("Request")}} 对象,也可以是 URL。
+
+ +

返回值

+ +

void返回值的 {{jsxref("Promise")}} 

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionHappens when
TypeError +

URL的协议不是 http 或 https。

+ +

请求返回的http状态码不是2xx (不是一个成功的响应) 。这种情况常常发生在请求不成功,或者是一个没有配置CORS的跨域请求(这种情况下返回的状态码永远是0)。

+
+ +

示例

+ +

下面的代码块等待 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装过程。 包括调用 {{domxref("CacheStorage.open")}} 来创建一个新的缓存,然后使用 {{domxref("Cache.add")}} 来添加一个请求资源到该缓存。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.add('/sw-test/index.html');
+    })
+  );
+});
+
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatNo}}24{{CompatNo}}
Require HTTPS{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatGeckoDesktop(47.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(46.0)}}
Require HTTPS{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/addall/index.html b/files/zh-cn/web/api/cache/addall/index.html new file mode 100644 index 0000000000..fad889eab9 --- /dev/null +++ b/files/zh-cn/web/api/cache/addall/index.html @@ -0,0 +1,202 @@ +--- +title: Cache.addAll() +slug: Web/API/Cache/addAll +translation_of: Web/API/Cache/addAll +--- +

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

+ +

概要

+ +

{{domxref("Cache")}} 接口的 addAll() 方法接受一个URL数组,检索它们,并将生成的response对象添加到给定的缓存中。 在检索期间创建的request对象成为存储的response操作的key。

+ +
+

NoteaddAll() will overwrite any key/value pairs previously stored in the cache that match the request, but will fail if a resulting put() operation would overwrite a previous cache entry created by the same addAll() method.

+
+ +
+

Note: Initial Cache implementations (in both Blink and Gecko) resolve {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, and {{domxref("Cache.put")}} promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

+
+ +

语法

+ +
cache.addAll(requests[]).then(function() {
+  //requests have been added to the cache
+});
+
+ +

参数

+ +
+
requests
+
要获取并添加到缓存的字符串URL数组。
+
+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves with void.

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionHappens when
TypeError +

The URL scheme is not http or https.

+ +

The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.)

+
+ +

示例

+ +

此代码块等待一个 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装进程。 包括调用 {{domxref("CacheStorage.open")}} 创建一个新的cache,然后使用 addAll() 添加一系列资源。

+ +
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'
+      ]);
+    })
+  );
+});
+
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatNo}}24{{CompatNo}}
Require HTTPS{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatGeckoDesktop(47.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(46.0)}}
Require HTTPS{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/delete/index.html b/files/zh-cn/web/api/cache/delete/index.html new file mode 100644 index 0000000000..f6b20ab981 --- /dev/null +++ b/files/zh-cn/web/api/cache/delete/index.html @@ -0,0 +1,150 @@ +--- +title: Cache.delete() +slug: Web/API/Cache/delete +tags: + - API + - Cache +translation_of: Web/API/Cache/delete +--- +

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

+ +

{{domxref("Cache")}} 接口的 delete() 方法查询request为key的 {{domxref("Cache")}} 条目,如果找到,则删除该 {{domxref("Cache")}} 条目并返回resolve为true的 {{jsxref("Promise")}} 。 如果没有找到,则返回resolve为false的 {{jsxref("Promise")}} 。

+ +

语法

+ +
cache.delete(request,{options}).then(function(true) {
+  //your cache entry has been deleted
+});
+
+ +

返回值

+ +

如果cache条目被删除,则返回resolve为true的 {{jsxref("Promise")}},否则,返回resolve为false的 {{jsxref("Promise")}}。

+ +

参数

+ +
+
request
+
请求删除的 {{domxref("Request")}}。
+
options {{optional_inline}}
+
一个对象,其属性控制删除操作中如何处理匹配缓存。可用的选项是: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值,指定匹配进程中是否忽略url中的查询字符串。如果设置为true,http://foo.com/?value=bar 中的 ?value=bar 部分在执行匹配时会被忽略。默认为false。
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,当设置为true时,将阻止匹配操作验证{domxref("Request")}} HTTP方法(通常只允许GET和HEAD)。默认为false。
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,当设置为true时,告诉匹配操作不执行VARY头匹配。In other words, if the URL matches you will get a match regardless of  whether the {{domxref("Response")}} object has a VARY header. 默认为false。
  • +
  • cacheName: A {{domxref("DOMString")}} that represents a specific cache to search within. Note that this option is ignored by Cache.delete().
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.delete('/images/image.png').then(function(response) {
+    someUIUpdateFunction();
+  });
+})
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}[1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}{{CompatOpera(24)}}{{CompatNo}}
All options supported{{CompatChrome(54.0)}}  {{CompatOpera(41)}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}[1]
All options supported{{CompatNo}}{{CompatNo}}   {{CompatOperaMobile(41)}} {{CompatChrome(54.0)}}
+
+ +

[1] The options parameter only supports ignoreSearch, and cacheName

+ +

[2] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/index.html b/files/zh-cn/web/api/cache/index.html new file mode 100644 index 0000000000..9e51499607 --- /dev/null +++ b/files/zh-cn/web/api/cache/index.html @@ -0,0 +1,282 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Cache + - Offline + - Service Workers + - Storage +translation_of: Web/API/Cache +--- +

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

+ +

Cache 接口为缓存的 Request / Response  对象对提供存储机制,例如,作为{{domxref("ServiceWorker")}} 生命周期的一部分。请注意,Cache 接口像 workers 一样,是暴露在 window 作用域下的。尽管它被定义在 service worker 的标准中,  但是它不必一定要配合 service worker 使用.

+ +

一个域可以有多个命名 Cache 对象。你需要在你的脚本 (例如,在 {{domxref("ServiceWorker")}} 中)中处理缓存更新的方式。除非明确地更新缓存,否则缓存将不会被更新;除非删除,否则缓存数据不会过期。使用 {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} 打开一个Cache 对象,再使用 Cache 对象的方法去处理缓存.

+ +

你需要定期地清理缓存条目,因为每个浏览器都硬性限制了一个域下缓存数据的大小。缓存配额使用估算值,可以使用 {{domxref("StorageEstimate")}} API 获得。浏览器尽其所能去管理磁盘空间,但它有可能删除一个域下的缓存数据。浏览器要么自动删除特定域的全部缓存,要么全部保留。确保按名称安装版本缓存,并仅从可以安全操作的脚本版本中使用缓存。查看 Deleting old caches 获取更多信息.

+ +
+

Note: {{domxref("Cache.put")}}, {{domxref("Cache.add")}}和{{domxref("Cache.addAll")}}只能在GET请求下使用。

+
+ +
+

Note: Initial Cache implementations (in both Blink and Gecko) resolve {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, and {{domxref("Cache.put")}} promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

+
+ +
+

Note: 自Chrome 46版本起,Cache API只保存安全来源的请求,即那些通过HTTPS服务的请求。

+
+ +
+

Note: The key matching algorithm depends on the VARY header in the value. So matching a new key requires looking at both key and value for entries in the Cache.

+
+ +
+

Note: Cache API不支持HTTP缓存头。

+
+ +

方法

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
返回一个 {{jsxref("Promise")}}对象,resolve的结果是跟 {{domxref("Cache")}} 对象匹配的第一个已经缓存的请求。
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
返回一个{{jsxref("Promise")}} 对象,resolve的结果是跟{{domxref("Cache")}}对象匹配的所有请求组成的数组。
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
抓取这个URL, 检索并把返回的response对象添加到给定的Cache对象.这在功能上等同于调用 fetch(), 然后使用 Cache.put() 将response添加到cache中.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
抓取一个URL数组,检索并把返回的response对象添加到给定的Cache对象。
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
同时抓取一个请求及其响应,并将其添加到给定的cache。
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
搜索key值为request的{{domxref("Cache")}} 条目。如果找到,则删除该{{domxref("Cache")}} 条目,并且返回一个resolve为true的{{jsxref("Promise")}}对象;如果未找到,则返回一个resolve为false的{{jsxref("Promise")}}对象。
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
返回一个{{jsxref("Promise")}}对象,resolve的结果是{{domxref("Cache")}}对象key值组成的数组。
+
+ +

示例

+ +

此代码段来自 service worker selective caching sample. (请参阅 selective caching live) 。该代码使用{{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} 打开任何具有以font/开始的Content-Type头的{{domxref("Cache")}}对象。

+ +

代码然后使用{{domxref("Cache.match", "Cache.match(request, options)")}}查看缓存中是否已经有一个匹配的font,如果是,则返回它。 如果没有匹配的字体,代码将通过网络获取字体,并使用 {{domxref("Cache.put","Cache.put(request, response)")}}来缓存获取的资源。

+ +

代码处理从{{domxref("Globalfetch.fetch","fetch()")}} 操作抛出的异常。 请注意,HTTP错误响应(例如404)不会触发异常。 它将返回一个具有相应错误代码集的正常响应对象。

+ +

该代码片段还展示了服务工作线程使用的缓存版本控制的最佳实践。 虽然在这个例子中只有一个缓存,但同样的方法可用于多个缓存。 它将缓存的速记标识符映射到特定的版本化缓存名称。 代码还会删除命名不在CURRENT_CACHES中的所有缓存。

+ +
注意: 在Chrome中,请访问chrome://inspect/#service-workers ,然后单击注册的服务工作线程下面的“inspect”链接,查看 service-worker.js 脚本正在执行的各种操作的日志记录。
+ +
var CACHE_VERSION = 1;
+
+// 简写标识符映射到特定版本的缓存。
+var CURRENT_CACHES = {
+  font: 'font-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('activate', function(event) {
+  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
+    return CURRENT_CACHES[key];
+  });
+
+  // 在promise成功完成之前,活跃的worker不会被视作已激活。
+  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('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+
+    // 打开以'font'开头的Cache对象。
+    caches.open(CURRENT_CACHES['font']).then(function(cache) {
+      return cache.match(event.request).then(function(response) {
+        if (response) {
+          console.log(' Found response in cache:', response);
+
+          return response;
+        }
+      }).catch(function(error) {
+
+        // 处理match()或fetch()引起的异常。
+        console.error('  Error in fetch handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{CompatGeckoDesktop(39)}}[1]{{CompatNo}}24{{CompatNo}}
add(){{CompatChrome(44.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
addAll(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
matchAll(){{CompatChrome(47.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Require HTTPS for add(), addAll(), and put(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
add(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(44.0)}}
addAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
matchAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
Require HTTPS for add(), addAll(), and put(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/keys/index.html b/files/zh-cn/web/api/cache/keys/index.html new file mode 100644 index 0000000000..10be6eb859 --- /dev/null +++ b/files/zh-cn/web/api/cache/keys/index.html @@ -0,0 +1,136 @@ +--- +title: Cache.keys() +slug: Web/API/Cache/keys +translation_of: Web/API/Cache/keys +--- +

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

+ +

 {{domxref("Cache")}} 接口的 keys() 方法返回一个 {{jsxref("Promise")}} ,这个 {{jsxref("Promise")}} 将解析为一个{{domxref("Cache")}} 键的数组。

+ +

请求将以它们被插入的顺序返回。

+ +
+

注意: 具有相同URL但不同请求头的请求,如果它们的响应头中有 VARY 头部,则他们可以被返回。

+
+ +

语法

+ +
cache.keys(request,{options}).then(function(keys) {
+  //do something with your array of requests
+});
+
+ +

返回值

+ +

返回一个解析为 {{domxref("Cache")}} 键数组的 {{jsxref("Promise")}}。

+ +

参数

+ +
+
request {{optional_inline}}
+
如果一个相关键被指定,则返对应的 {{domxref("Request")}} 。
+
options {{optional_inline}}
+
一个对象,它的属性决定了 keys 操作中的匹配操作是如何执行的。可选的属性有: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值,指定了匹配操作是否忽略url中的查询部分。如果为 true ,在执行匹配操作时, http://foo.com/?value=bar 的 ?value=bar 部分将会被忽。默认为 false 。
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,当为 true 时, 将会阻止匹配操作验证 {{domxref("Request")}} 的 HTTP 方法(通常只有 GET 和 HEAD 方法被允许)。默认为 false 。
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,当为 true 时,告诉匹配操作不要验证 VARY 头部。换句话说,如果 URL 匹配,你会得到一个匹配而不管 {{domxref("Response")}} 对象是否有 VARY 头部。默认为 false 。
  • +
  • cacheName: 一个 {{domxref("DOMString")}} 值,描述了在一个特定的 cache 中进行匹配。注意这个选项会被 Cache.keys()方法忽略。
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.keys().then(function(keys) {
+    keys.forEach(function(request, index, array) {
+      cache.delete(request);
+    });
+  });
+})
+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}[1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}[1]
+
+ +

[1] 可选参数只支持 ignoreSearch 和 cacheName 

+ +

[2] Service workers (以及Push) 在 Firefox 45 Extended Support Release (ESR) 中已经被禁止了。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cache/match/index.html b/files/zh-cn/web/api/cache/match/index.html new file mode 100644 index 0000000000..6670556654 --- /dev/null +++ b/files/zh-cn/web/api/cache/match/index.html @@ -0,0 +1,173 @@ +--- +title: Cache.match() +slug: Web/API/Cache/match +tags: + - Cache.match() + - ServiceWorker + - match + - 实验性的 +translation_of: Web/API/Cache/match +--- +

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

+ +

{{domxref("Cache")}} 接口的 match() 方法, 返回一个 {{jsxref("Promise")}} 解析为(resolve to)与 {{domxref("Cache")}} 对象中的第一个匹配请求相关联的{{domxref("Response")}} 。如果没有找到匹配,{{jsxref("Promise")}} 解析为 {{jsxref("undefined")}}。

+ +

语法

+ +
cache.match(request,{options}).then(function(response) {
+  //操作response
+});
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}} 对象,该对象解析为第一个匹配请求的 {{domxref("Response")}} 对象,如果没有匹配到,则解析到 {{jsxref("undefined")}} 。

+ +
+

Note: Cache.match() 基本上和 {{domxref("Cache.matchAll()")}} 一样, 只不过 Cache.match() 只解析为 response[0] (第一个匹配的响应(response)对象) 而不是 response[] (所有响应对象组成的数组)。

+
+ +

参数

+ +
+
request
+
在{{domxref("Cache")}}对象中查找的{{domxref("Request")}}对象对应的response。这个{{domxref("Request")}}可以是 object 或者是一个URL.
+
options {{optional_inline}}
+
一个为 match 操作设置选项的对象。有效的选项如下: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值用来设置是否忽略url中的query部分。例如, 如果该参数设置为 true ,那么 http://foo.com/?value=bar中的 ?value=bar 部分就会在匹配中被忽略. 该选项默认为 false
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,如果设置为 true在匹配时就不会验证 {{domxref("Request")}} 对象的http 方法 (通常只允许是 GET 或 HEAD 。) 该参数默认值为 false
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,该值如果为 true 则匹配时不进行 VARY 部分的匹配。例如,如果一个URL匹配,此时无论{{domxref("Response")}}对象是否包含VARY头部,都会认为是成功匹配。该参数默认为 false
  • +
  • cacheName: 一个 {{domxref("DOMString")}} ,代表一个具体的要被搜索的缓存。注意该选项被 Cache.match()方法忽略。
  • +
+
+
+ +

例子

+ +

这个是个来自 custom offline page 的例子 (live demo)。

+ +

下面的例子在请求失败时提供特定的数据。 catch() 在 fetch() 的调用抛出异常时触发。在 catch() 语句中, match()用来返回正确的响应。

+ +

在这个例子中,我们决定只缓存通过GET取得的HTML文档. 如果 if() 条件是 false,那么这个fetch处理器就不会处理这个请求。如果还有其他的fetch处理器被注册,它们将有机会调用 event.respondWith() 如果没有fetch处理器调用 event.respondWith() ,该请求就会像没有 service worker 介入一样由浏览器处理。如果 fetch() 返回了有效的HTTP响应,相应码是4xx或5xx,那么catch() 就不会被调用。

+ +
self.addEventListener('fetch', function(event) {
+  // 我们只想在用GET方法请求HTML文档时调用 event.respondWith()。
+  if (event.request.method === 'GET' &&
+      event.request.headers.get('accept').indexOf('text/html') !== -1) {
+    console.log('Handling fetch event for', event.request.url);
+    event.respondWith(
+      fetch(event.request).catch(function(e) {
+        console.error('Fetch failed; returning offline page instead.', e);
+        return caches.open(OFFLINE_CACHE).then(function(cache) {
+          return cache.match(OFFLINE_URL);
+        });
+      })
+    );
+  }
+});
+ +

规范

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

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}} [1]{{CompatGeckoDesktop(39)}}[2]{{CompatNo}}{{CompatOpera(24)}}{{CompatNo}}
All options supported{{CompatChrome(54.0)}}{{CompatOpera(41)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(40.0)}} [1]
All options supported{{CompatNo}}{{CompatNo}}{{CompatOperaMobile(41)}}{{CompatChrome(54.0)}}
+
+ + + +

参阅

+ + diff --git a/files/zh-cn/web/api/cache/matchall/index.html b/files/zh-cn/web/api/cache/matchall/index.html new file mode 100644 index 0000000000..bfb069914d --- /dev/null +++ b/files/zh-cn/web/api/cache/matchall/index.html @@ -0,0 +1,82 @@ +--- +title: Cache.matchAll() +slug: Web/API/Cache/matchAll +translation_of: Web/API/Cache/matchAll +--- +

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

+ +

{{domxref("Cache")}} 接口的 matchAll() 方法返回一个 {{jsxref("Promise")}} ,其 resolve 为 {{domxref("Cache")}} 对象中所有匹配请求的数组。

+ +

语法

+ +
cache.matchAll(request,{options}).then(function(response) {
+  //do something with the response array
+});
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}},resolve为 {{domxref("Cache")}} 对象中所有匹配请求的数组。

+ +
+

注意: {{domxref("Cache.match()")}} 基本上与Cache.matchAll() 相同,除了它 resolve 为 response[0] (即第一个匹配响应) 而不是 response (数组中所有匹配的响应)。

+
+ +

参数

+ +
+
request {{optional_inline}}
+
{{domxref("Cache")}} 中你尝试查找的The {{domxref("Request")}} . 如果忽略这一参数,你将获取到cache中所有 response 的副本。
+
options {{optional_inline}}
+
一个选项对象,允许你为 match 操作中要做的匹配设置特定控制选项。可用选项包括: +
    +
  • ignoreSearch: 一个 {{domxref("Boolean")}} 值用来设置匹配操作是否忽略url中的query部分。如果该参数设置为 true ,那么 http://foo.com/?value=bar 中的 ?value=bar 部分就会在匹配中被忽略. 该选项默认为 false
  • +
  • ignoreMethod: 一个 {{domxref("Boolean")}} 值,如果设置为 true在匹配时就不会验证 {{domxref("Request")}} 对象的http 方法 (通常只允许是 GET 或 HEAD 。) 该参数默认值为 false
  • +
  • ignoreVary: 一个 {{domxref("Boolean")}} 值,该值如果为 true 则匹配时不进行 VARY 部分的匹配。例如,如果一个URL匹配,此时无论{{domxref("Response")}}对象是否包含VARY头部,都会认为是成功匹配。该参数默认为 false
  • +
  • cacheName: 一个 {{domxref("DOMString")}} ,代表一个具体的要被搜索的缓存。注意该选项被Cache.matchAll()方法忽略。
  • +
+
+
+ +

示例

+ +
caches.open('v1').then(function(cache) {
+  cache.matchAll('/images/').then(function(response) {
+    response.forEach(function(element, index, array) {
+      cache.delete(element);
+    });
+  });
+})
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#dom-cache-matchall', 'Cache: matchAll')}}{{Spec2('Service Workers')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Cache.matchAll")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/cache/put/index.html b/files/zh-cn/web/api/cache/put/index.html new file mode 100644 index 0000000000..24974d98fc --- /dev/null +++ b/files/zh-cn/web/api/cache/put/index.html @@ -0,0 +1,109 @@ +--- +title: Cache.put() +slug: Web/API/Cache/put +translation_of: Web/API/Cache/put +--- +

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

+ +

{{domxref("Cache")}} 接口的  put() 方法 允许将键/值对添加到当前的 {{domxref("Cache")}} 对象中.

+ +

通常,你只想 {{domxref("GloblFetch.fetch","fetch()")}} 一个或多个请求,然后直接添加结果到cache中。这种情况下,最好使用 {{domxref("Cache.add","Cache.add()")}}/{{domxref("Cache.addAll","Cache.addAll()")}},因为它们是一个或者多个这些操作的便捷方法。

+ +
fetch(url).then(function(response) {
+  if (!response.ok) {
+    throw new TypeError('Bad response status');
+  }
+  return cache.put(url, response);
+})
+
+
+ +
+

注意: put() 将覆盖先前存储在匹配请求的cache中的任何键/值对。

+
+ +
+

注意: {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} 不会缓存 Response.status 值不在200范围内的响应,而 {{domxref("Cache.put")}} 允许你存储任何请求/响应对。因此,{{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} 不能用于不透明的响应,而 {{domxref("Cache.put")}} 可以。

+
+ +
+

注意: 当响应主体完全写入磁盘时,初始Cache执行 (在 Blink 和 Gecko中) resolve {{domxref("Cache.add")}}、{{domxref("Cache.addAll")}} 和 {{domxref("Cache.put")}} promise.  更新的规范版本中声明:即使响应主体仍在流式传输,一旦条目被记录到数据库中,浏览器就可以 resolve promise.

+
+ +

语法

+ +
cache.put(request, response).then(function() {
+  // request/response pair has been added to the cache
+});
+
+ +

参数

+ +
+
request
+
The {{domxref("Request")}} you want to add to the cache.
+
response
+
The {{domxref("Response")}} you want to match up to the request.
+
+ +

返回值

+ +

A {{jsxref("Promise")}} that resolves with void.

+ +
+

Note: The promise will reject with a TypeError if the URL scheme is not http or https.

+
+ +

示例

+ +

This example is from the MDN sw-test example (see sw-test running live). Here 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 {{domxref("CacheStorage")}} using {{domxref("CacheStorage.match","CacheStorage.match()")}}. If so, serve that.
  2. +
  3. If not, open the v1 cache using open(), put the default network request in the cache using {{domxref("Cache.put","Cache.put()")}} and return a clone of the default network request using return response.clone(). Clone is needed because put() consumes the response body.
  4. +
  5. If this fails (e.g., because the network is down), return a fallback response.
  6. +
+ +
var response;
+var cachedResponse = caches.match(event.request).catch(function() {
+  return fetch(event.request);
+}).then(function(r) {
+  response = r;
+  caches.open('v1').then(function(cache) {
+    cache.put(event.request, response);
+  });
+  return response.clone();
+}).catch(function() {
+  return caches.match('/sw-test/gallery/myLittleVader.jpg');
+});
+ +

规范

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

浏览器兼容性

+ + + +

{{Compat("api.Cache.put")}}

+ +

See also

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