我有一个使用 File System Access API 读写本地文件的 create-react-app .在浏览器(支持它的 Chrome 或 Edge)中运行时,读取和写入文件都可以正常工作。
当应用程序在 Electron 中运行时,读取工作正常但写入失败,原因是:Uncaught (in promise) DOMException: The request is not allowed by the user agent or the platform in the current context.
我正在使用最新的 Electron (12.0.1),它使用与我的 Chrome 浏览器中相同的 Chromium (89.0.4389.82)。
下面是相关代码。 requestPermission
之后的控制台日志通话节目true
和 granted
在浏览器和true
和 denied
在 Electron 。
我尝试禁用 webSecurity
创建时BrowserWindow
, 使用 appendSwitch
禁用沙箱但没有任何帮助。
有没有办法给 Electron 中的 Chromium 更多权限?
如果没有,我愿意在 Electron 中以不同的方式处理文件写入。在这种情况下,写什么来代替 TODO
在代码中?请注意,因为它是一个 create-react-app,fs
模块是 not available .
export async function chooseAndReadFile() {
const fileHandle = await window.showOpenFilePicker().then((handles) => handles[0])
const file = await fileHandle.getFile()
const contents = await file.text()
return contents
}
export async function chooseAndWriteToFile(contents: string) {
const fileHandle = await window.showSaveFilePicker()
const descriptor: FileSystemHandlePermissionDescriptor = {
writable: true,
mode: "readwrite"
}
const permissionState = await fileHandle.requestPermission(descriptor)
console.log(window.isSecureContext)
console.log(permissionState)
const writable = await fileHandle.createWritable()
await writable.write(contents)
await writable.close()
}
let isElectron = require("is-electron")
export async function chooseAndWriteToFileUniversal(contents: string) {
if (isElectron()) {
// TODO: Do what???
} else {
chooseAndWriteToFile(contents)
}
}
最佳答案
回答我自己的问题,我终于使用了 HTML download
的解决方案属性,描述得很好here .当在 Electron 中使用这种技术时,它会显示一个文件保存对话框,这正是我想要的。当在浏览器中使用时,这种技术只是在没有提示的情况下下载文件,因此我将继续在浏览器环境中使用文件系统访问 API。
这是在 Electron 中运行时处理下载的代码。
function download(filename: string, contents: string) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
let isElectron = require("is-electron");
export async function chooseAndWriteToFileUniversal(contents: string) {
if (isElectron()) {
download("data.txt", contents)
} else {
chooseAndWriteToFile(contents) // See the original question for implementation of this function
}
}
不过,很高兴知道 Electron 中的 Chromium 为什么/如何比普通的 Chrome 或 Edge 浏览器更受限制,以及是否可以更改。
关于reactjs - 在 Electron + Create React App 中使用文件系统访问 API 写入文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66661551/