contextBridge
在隔离的上下文中创建一个安全的、双向的、同步的桥梁。
进程: Renderer
如下,是一个从隔离的预加载脚本将 API 暴露给渲染器的示例:
// Preload (Isolated World)
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
// Renderer (Main World)
window.electron.doThing()
词汇表
Main World
"Main World"是主渲染器代码运行的 JavaScript 上下文。 默认情况下,你在渲染器中加载的页面在此环境中执行代码。
Isolated World
当你在webPreferences
属性中启用contextIsolation
(Electron 12.0.0 及以上版本默认启用),你的预加载
脚本将运行在一个“被隔离的环境”中。 您可以在Security 文档中阅读更多关于上下文隔离及其影响的信息。
方法
contextBridge
模块有以下方法:
contextBridge.exposeInMainWorld(apiKey, api)
apiKey
string - 将 API 注入到窗口
的键。 API 将可通过window[apiKey]
访问。api
any - 你的 API可以是什么样的以及它是如何工作的相关信息如下。
contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)
worldId
Integer - 要注入 API 的 world 的 ID。0
是默认 world,999
的 world 被 Electron 的contextIsolation
使用。 使用 999 would 为 preload 上下文暴露对象。 我们建议使用 1000+ 来创建隔离的 world。apiKey
string - 将 API 注入到window
的键。 API 将可通过window[apiKey]
访问。api
any - 你的 API可以是什么样的以及它是如何工作的相关信息如下。