webUtils¶
一个用于与 Web API 对象(File、Blob 等)交互的工具层。
进程:渲染进程
[!IMPORTANT] 如果要在启用了上下文隔离的渲染进程中调用此 API,请在预加载脚本中调用该 API,并使用
contextBridgeAPI 将其暴露出来。
方法¶
webUtils 模块有以下方法:
webUtils.getPathForFile(file)¶
fileFile - 一个 Web File 对象。
返回 string - 此 File 对象指向的文件系统路径。如果传入的对象不是 File 对象,则会抛出异常。如果传入的 File 对象是在 JS 中构造的,且没有磁盘上的文件作为支持,则返回空字符串。
此方法取代了之前通过 path 属性对 File 对象的增强。下面是一个示例。
```js @ts-nocheck // 之前(渲染进程) const oldPath = document.querySelector('input[type=file]').files[0].path
```js @ts-nocheck
// 之后
// 渲染进程:
const file = document.querySelector('input[type=file]').files[0]
electronApi.doSomethingWithFile(file)
// 预加载脚本:
const { contextBridge, webUtils } = require('electron')
contextBridge.exposeInMainWorld('electronApi', {
doSomethingWithFile(file) {
const path = webUtils.getPathForFile(file)
// 对该路径执行某些操作,例如通过 IPC 将其发送到主进程。
// 如果可能,最好不要将完整文件路径暴露给 Web 内容。
}
})
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron