-
Notifications
You must be signed in to change notification settings - Fork 310
Closed
Labels
P1🔥 重要但是不紧急的内容🔥 重要但是不紧急的内容
Description
OPFS
-
MDN (English): https://developer.mozilla.org/en/docs/Web/API/File_System_API/Origin_private_file_system
-
MDN (中文): https://developer.mozilla.org/zh-CN/docs/Web/API/File_System_API/Origin_private_file_system
OPFS 提供了页面所属源私有的、对用户不可见的、底层的逐字节文件访问能力。 因此它不需要经过与调用文件系统访问 API 所需的一系列相同的安全性检查和授权,而且比文件系统访问 API 更快。 它还有一套同步调用方法可用(其他的文件系统 API 调用是异步的),但只能在 web worker 中运行,这样就不会阻塞主线程。 概括 OPFS 和用户可见文件系统的不同: OPFS 和其他源分区存储机制(例如 [IndexedDB API])一样,受到[浏览器存储配额限制]。 你可以通过 [navigator.storage.estimate()] 来获得 OPFS 所用的存储空间的容量。 清除站点的存储数据会删除 OPFS。 访问 OPFS 中的文件不需要权限提示和安全性检查。 浏览器会把 OPFS 的内容持久化保存在磁盘的某个位置,但你不能指望能够一一对应地找到创建出的文件。OPFS 对用户不可见。
应用
以下代码必须在 chrome-extension://<extension-id>/ 中执行 (offscreen, extension pages, service_worker)
// 储存
const OPFS_ROOT = await navigator.storage.getDirectory();
const filename = uuidv4();
const directoryHandle = await OPFS_ROOT.getDirectoryHandle("CACHED_IMAGES", { create: true });
const handle = await directoryHandle.getFileHandle(filename, { create: true });
const writable = await handle.createWritable();
await writable.write(data);
await writable.close();
return filename;这样的话,data (例如blob) 就会直接储在 chrome-extension://<extension-id>/ 的 Origin Private File System (OPFS)
// 读取。注意要 try-catch 处理 NotFoundError (目录或档案不存在)
const OPFS_ROOT = await navigator.storage.getDirectory();
const directoryHandle = await OPFS_ROOT.getDirectoryHandle("CACHED_IMAGES");
const handle = await directoryHandle.getFileHandle(filename);
const file = await handle.getFile(); // 这个 file 内容是之前储存的blob, 档案名是 filename
return file; // 有需要可以用 URL.createObjectURL(file) 转化成 blobURL其他resource files 也可以这样做
不过现在, 图档用OPFS做合适 (需要blob存取而非文字存取,都在后台/扩展页面使用)
// 清档案用 (整个 CACHED_IMAGES 删掉)。注意要 try-catch 处理 NotFoundError (目录或档案不存在)
await OPFS_ROOT.removeEntry("CACHED_IMAGES", { recursive: true });CodFrm
Metadata
Metadata
Assignees
Labels
P1🔥 重要但是不紧急的内容🔥 重要但是不紧急的内容