ast*_*ums 9 file reactjs electron create-react-app file-system-access-api
我有一个 create-react-app 使用File System Access API读取和写入本地文件。当在浏览器(支持它的 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)。
下面是相关代码。调用后的控制台日志在浏览器和Electron中requestPermission显示true和。grantedtruedenied
我尝试webSecurity在创建时禁用BrowserWindow,禁用沙箱,appendSwitch但没有任何帮助。
有没有办法给Electron中的Chromium更多的权限?
如果没有,我愿意在 Electron 中以不同的方式处理文件写入。那么,TODO在代码中应该写什么来代替呢?请注意,因为它是一个 create-react-app,所以该fs模块不可用。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
回答我自己的问题,我最终使用了带有 HTML 属性的解决方案download,这里有很好的描述。当这种技术在 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
}
}
Run Code Online (Sandbox Code Playgroud)
尽管如此,还是很高兴知道为什么/如何在 Electron 中 Chromium 比在普通 Chrome 或 Edge 浏览器中受到更多限制,以及是否可以更改。
| 归档时间: |
|
| 查看次数: |
2277 次 |
| 最近记录: |