实现说明
除了函数 used、cap、headroom,文件里再无其他定义。
await 点把异步工作排成序列,拒绝落在取结果的那一行。
使用要点
- 这是浏览器侧代码——
navigator在 Node 里解析不到。 - 直接运行文件,输出会带上标签,比如
StorageManager unavailable in this context——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 used、cap、headroom。
入口签名:const used = (usage / 2 ** 20)
核心语句
const { usage = 0, quota = 0 } = await manager.estimate();
const persisted = await manager.persisted();
代码示例
// StorageManager.estimate() reports origin usage and quota asynchronously
const manager = navigator.storage;
if (!manager || typeof manager.estimate !== 'function') {
console.log('StorageManager unavailable in this context');
} else {
const { usage = 0, quota = 0 } = await manager.estimate();
const used = (usage / 2 ** 20).toFixed(1);
const cap = (quota / 2 ** 20).toFixed(1);
const headroom = ((quota - usage) / 2 ** 20).toFixed(1);
console.log('used MB:', used, '| quota MB:', cap, '| headroom MB:', headroom);
// persisted() reads whether the origin already keeps storage under pressure
const persisted = await manager.persisted();
console.log('persisted storage:', persisted);
}