这篇翻译不完整。请帮忙从英语翻译这篇文章。
这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
CacheStorage
接口(可适用于全局性caches
) 的 match()
方法检查给定的Request
对象或url字符串是否是一个已存储的 Response
对象的key. 这个方法针对 Response
返回一个 Promise
,如果没有匹配则返回 undefined
。
cache对象按创建顺序查询。
语法
caches.match(request, options).then(function(response) { // Do something with the response });
参数
- request
- 想要匹配的
Request
。这个参数可以是Request
对象或 URL 字符串。 - options 可选
- 这个对象中的属性控制在匹配操作中如何进行匹配选择。可选择参数如下:
ignoreSearch
:Boolean
值, 指定匹配过程是否应该忽略url中查询参数。举个例子,如果该参数设置为true
, 那么?value=bar
作为http://foo.com/?value=bar
中的查询参数将会在匹配过程中被忽略。该参数默认false
。ignoreMethod
:Boolean
值,当被设置为true
时,将会阻止在匹配操作中对Request
请求的http
方式的验证 (通常只允许GET
和HEAD
两种请求方式)。该参数默认为false
.ignoreVary
:Boolean
值,当该字段被设置为true,
告知在匹配操作中忽略对VARY
头信息的匹配。换句话说,当请求 URL 匹配上,你将获取匹配的Response
对象,无论请求的VARY
头存在或者没有。该参数默认为false
.cacheName
:DOMString
值, 表示所要搜索的缓存名称。
返回值
返回resolve为匹配 Response
的 Promise
对象。如果没有与指定request相匹配response,promise将使用 undefined
resolve.
例子
此示例来自于MDN sw-test example (请参阅 sw-test running live)。这里,等待 FetchEvent
事件触发。我们构建自定义响应,像这样:
- 使用
CacheStorage.match()
检查CacheStorage
中是否存在匹配请求,如果存在,则使用它。 - 如果没有,使用
open()
打开v1
cache,使用Cache.put()
将默认网络请求放入 cache 中,并只用return response.clone()
返回默认网络请求的克隆副本。最后一个是必须的,因为put()
使用响应主体。 - 如果此操作失败(例如,因为网络已关闭),则返回备用响应。
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 |
---|---|---|
Service Workers CacheStorage |
Working Draft | Initial definition. |
浏览器兼容性
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Basic support | Chrome
Full support
54
| Edge Full support 16 | Firefox
Full support
44
| IE No support No | Opera
Full support
41
| Safari Full support 11.1 | WebView Android
Full support
54
| Chrome Android
Full support
54
| Edge Mobile Full support Yes | Firefox Android Full support 44 | Opera Android
Full support
41
| Safari iOS Full support Yes | Samsung Internet Android ? |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
- Experimental. Expect behavior to change in the future.
- Experimental. Expect behavior to change in the future.
- See implementation notes.
- See implementation notes.