`title: File System Access API 与 OPFS 权限与兼容性``categories: Web 开发/前端/数据管理``keywords: File System Access API,OPFS,权限,兼容性,安全,性能``description: 介绍 OPFS 的能力与在主线程/Worker 的读写方式、权限模型与兼容性检测,并提供经过验证的代码片段与回退方案。`OPFS 是什么OPFS(Origin Private File System)为站点提供隔离的私有文件系统,适合大型二进制或文档持久化。兼容性与检测特性检测:`navigator.storage && navigator.storage.getDirectory`。Chromium 系列稳定支持;Firefox/Safari 新版逐步支持,建议运行时检测并回退。async function hasOPFS() {

return !!(navigator.storage && navigator.storage.getDirectory);

}

主线程写入(异步流)async function writeTextFile(name, content) {

const root = await navigator.storage.getDirectory();

const handle = await root.getFileHandle(name, { create: true });

const writable = await handle.createWritable();

await writable.write(new Blob([content], { type: 'text/plain; charset=utf-8' }));

await writable.close();

}

Worker 中的同步句柄`FileSystemSyncAccessHandle` 仅在 `DedicatedWorker` 或 `SharedWorker` 可用,避免主线程阻塞。// worker.js

self.addEventListener('message', async (e) => {

const { name, bytes } = e.data;

const root = await navigator.storage.getDirectory();

const handle = await root.getFileHandle(name, { create: true });

const sync = await handle.createSyncAccessHandle();

try {

const written = sync.write(bytes); // Uint8Array

sync.flush();

self.postMessage({ ok: true, written });

} finally {

sync.close();

}

});

权限与安全OPFS 不需要用户选择文件对话框;由站点沙箱管理,跨站不可见。清理:通过 `root.removeEntry(name, { recursive: true })` 删除;遵守隐私策略与配额管理。回退方案无 OPFS 时:使用 IndexedDB 存储二进制(Blob)或分块;或使用 Cache Storage 缓存静态资产。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部