--- title: CacheStorage.match() slug: Web/API/CacheStorage/match translation_of: Web/API/CacheStorage/match ---

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

{{domxref("CacheStorage")}} 接口(可适用于全局性caches) 的 match() 方法检查给定的{{domxref("Request")}} 对象或url字符串是否是一个已存储的 {{domxref("Response")}} 对象的key. 这个方法针对 {{domxref("Response")}} 返回一个 {{jsxref("Promise")}} ,如果没有匹配则返回 undefined

cache对象按创建顺序查询。

提示: {{domxref("CacheStorage.match()", "caches.match()")}} 是一个便捷方法。其作用等同于在每个缓存上调用 {{domxref("cache.match()")}} 方法 (按照{{domxref("CacheStorage.keys()", "caches.keys()")}}返回的顺序) 直到返回{{domxref("Response")}} 对象。

语法

caches.match(request, options).then(function(response) {
  // Do something with the response
});

参数

request
想要匹配的 {{domxref("Request")}}。这个参数可以是 {{domxref("Request")}} 对象或 URL 字符串。
options {{optional_inline}}
这个对象中的属性控制在匹配操作中如何进行匹配选择。可选择参数如下:

返回值

返回resolve为匹配 {{domxref("Response")}} 的 {{jsxref("Promise")}} 对象。如果没有与指定request相匹配response,promise将使用 undefined resolve.

例子

此示例来自于MDN sw-test example (请参阅 sw-test running live)。这里,等待 {{domxref("FetchEvent")}} 事件触发。我们构建自定义响应,像这样:

  1. 使用 {{domxref("CacheStorage.match","CacheStorage.match()")}} 检查 {{domxref("CacheStorage")}} 中是否存在匹配请求,如果存在,则使用它。
  2. 如果没有,使用  open() 打开 v1 cache,使用 {{domxref("Cache.put","Cache.put()")}}  将默认网络请求放入 cache 中,并只用 return response.clone() 返回默认网络请求的克隆副本。最后一个是必须的,因为 put() 使用响应主体。
  3. 如果此操作失败(例如,因为网络已关闭),则返回备用响应。
caches.match(event.request).then(function(response) {
  return response || fetch(event.request).then(function(r) {
    caches.open('v1').then(function(cache) {
      cache.put(event.request, r);
    });
    return r.clone();
  });
}).catch(function() {
  return caches.match('/sw-test/gallery/myLittleVader.jpg');
});

规范

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

浏览器兼容性

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

亦可参考