Skip to main content

webUtils

与 Web API 对象(文件、Blob 等)交互的实用程序层

¥A utility layer to interact with Web API objects (Files, Blobs, etc.)

进程:渲染器

¥Process: Renderer

[!重要] 如果你想从启用了上下文隔离的渲染进程调用此 API,请将 API 调用放在预加载脚本中,并使用 contextBridge API 对其进行 expose 操作。

¥[!IMPORTANT] If you want to call this API from a renderer process with context isolation enabled, place the API call in your preload script and expose it using the contextBridge API.

方法

¥Methods

webUtils 模块有以下方法:

¥The webUtils module has the following methods:

webUtils.getPathForFile(file)

  • file 文件 - 一个 Web 文件 对象。

    ¥file File - A web File object.

返回 string - 该 File 对象指向的文件系统路径。如果传入的对象不是 File 对象,则会引发异常。如果传入的 File 对象是在 JS 中构造的并且不受磁盘上的文件支持,则返回空字符串。

¥Returns string - The file system path that this File object points to. In the case where the object passed in is not a File object an exception is thrown. In the case where the File object passed in was constructed in JS and is not backed by a file on disk an empty string is returned.

此方法取代了之前使用 path 属性对 File 对象的增强。下面包含一个示例。

¥This method superseded the previous augmentation to the File object with the path property. An example is included below.

// Before (renderer)
const oldPath = document.querySelector('input[type=file]').files[0].path
// After

// Renderer:

const file = document.querySelector('input[type=file]').files[0]
electronApi.doSomethingWithFile(file)

// Preload script:

const { contextBridge, webUtils } = require('electron')

contextBridge.exposeInMainWorld('electronApi', {
doSomethingWithFile (file) {
const path = webUtils.getPathForFile(file)
// Do something with the path, e.g., send it over IPC to the main process.
// It's best not to expose the full file path to the web content if possible.
}
})