
现代浏览器不支持直接通过 `navigator.permissions.query({ name: 'file-system' })` 获取“文件编辑”权限,该权限并不存在于当前标准中;实际应使用 file api 读取用户主动选择的文件,结合 `showsavefilepicker` 等 web apis 实现受控的读写操作。
在 Web 开发中,浏览器从未提供过名为 "file-system" 或 "file-editing" 的标准权限。你无法像请求地理位置或通知权限那样,通过 navigator.permissions.query({ name: 'file-system' }) 预先申请“编辑任意文件”的能力——这出于严格的安全沙箱原则:网页不能未经用户明确、逐次交互就访问本地文件系统。
✅ 正确做法是遵循 “用户手势驱动 + 显式选择” 模式:
- 读取文件:使用 让用户手动选择文件(触发 change 事件),再通过 FileReader 或 Blob.text()/arrayBuffer() 安全读取内容;
- 写入/保存文件:使用 Web File System Access API(Chrome 86+、Edge 86+、Firefox 125+ 支持)调用 showOpenFilePicker()(读)或 showSaveFilePicker()(写),每次操作均需用户点击确认。
以下是完整、可运行的示例代码(兼容现代浏览器):
<!DOCTYPE html> <html> <head><title>安全文件处理示例</title></head> <body> <h2>请选择一个文本文件进行处理</h2> <input type="file" id="fileInput" accept=".txt"> <button onclick="processFile()">处理文件</button> <button onclick="saveProcessedContent()">保存结果</button> <pre class="brush:php;toolbar:false;" id="output" style="background:#f5f5f5; padding:1em; max-height:200px; overflow:auto;"><script> let currentFileHandle = null; let processedContent = ""; async function processFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; if (!file) { alert("请先选择一个文件"); return; } try { // ✅ 安全读取:仅处理用户选中的文件 const text = aw<a style="color:#f60; text-decoration:underline;" title= "ai" href="https://www.php.cn/zt/17539.html" target="_blank">ait file.text(); processedContent = `[处理时间: ${new Date().toLocaleTimeString()}]\n${text.toUpperCase()}`; document.getElementById('output').textContent = processedContent; console.log("文件已读取并处理完成"); } catch (err) { console.error("读取失败:", err); alert("文件读取失败:" + err.message); } } // ✅ 写入文件:需用户主动触发保存对话框 async function saveProcessedContent() { if (!processedContent) return; try { // 调用保存文件选择器(用户必须点击确认) const handle = await <a style="color:#f60; text-decoration:underline;" title= "win" href="https://www.php.cn/zt/19041.html" target="_blank">window.showSaveFilePicker({ suggestedName: "processed-output.txt", types: [{ description: "Text Files", accept: { "text/plain": [".txt"] } }] }); const writable = await handle.createWritable(); await writable.write(processedContent); await writable.close(); alert("文件已成功保存!"); } catch (err) { // 用户取消保存或拒绝权限时捕获 DOMException if (err.name !== "AbortError") { console.error("保存失败:", err); alert("保存失败:" + err.message); } } } </script>










