Skip to main content

webUtils

一个用于与 Web API 对象(文件、Blob 等)交互的实用层

进程: 渲染器

🌐 Process: Renderer

info

如果你想从启用上下文隔离的渲染进程调用此 API, 请将 API 调用放在你的 preload 脚本中,并 使用 contextBridge API 暴露 它。

方法

🌐 Methods

webUtils 模块具有以下方法:

🌐 The webUtils module has the following methods:

webUtils.getPathForFile(file)

  • file 文件 - 一个网页 文件 对象。

返回 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.

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

🌐 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.
}
})