这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
keys
()
作为 CacheStorage
接口的方法返回一个 Promise
对象,该对象将被解析成一个包含Cache名称的字符串数组,当 Cache
对象在按照顺序创建时,会被CacheStorage
对象追踪。可以使用该方法遍历出所有的Cache
对象。
语法
caches.keys().then(function(keyList) { //对keyList做操作 });
返回
返回 CacheStorage
对象中 带Cache
名称数组的Promise
参数
无。
示例
在此代码片段中,我们通过监听activate
事件, 在事件中运行一个 waitUntil()
方法,该方法(event.waitUntil())作用是在新的service worker 被激活之前清除老的,无用的缓存。 这里我们设置一个包含缓存名称的白名单。 通过使用 keys()方法
来返回CacheStorage
对象中的keys集合, 然后检查缓存key判断是否在白名单中,如果不存在,则使用 CacheStorage.delete
方法来删除该缓存。
then.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } }); }) ); });
规范
Specification | Status | Comment |
---|---|---|
Service Workers CacheStorage |
Working Draft | Initial definition. |
浏览器兼容
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 40 | (Yes) | 44 (44)[1] | 未实现 | 27 | 未实现 |
Feature | Android Webview | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 40 | 40 | 44.0 (44) | (Yes) | 27 | (Yes) |
[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)