跳到主要内容

contextBridge

context-bridge,其实主要就是 exposeInMainWorld 方法。
在隔离的上下文中创建一个安全的、双向的、同步的桥梁。

进程: Renderer

// 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:是主渲染器代码运行的 JavaScript 上下文。 默认情况下,你在渲染器中加载的页面在此环境中执行代码。

  • Isolated World:当你在 webPreferences 属性中启用 contextIsolation (Electron 12.0.0 及以上版本默认启用),你的预加载脚本将运行在一个“被隔离的环境”中。您可以在 Security 文档中阅读更多关于上下文隔离及其影响的信息。

exposeInMainWorld

contextBridge.exposeInMainWorld(apiKey, api)
  • apiKey string - 将 API 注入到 窗口 的键。 API 将可通过 window[apiKey] 访问。
  • api any - 你的 API可以是什么样的以及它是如何工作的相关信息如下。

提供给 exposeInMainWorld 的 api 必须是一个 FunctionstringnumberArrayboolean;或 一个键为字符串,值为一个 Function, string, number, Array, boolean的对象;或其他符合相同条件的嵌套对象。

Function 类型的值被代理到其他上下文中,所有其他类型的值都会被 复制 并 冻结。 在 API 中发送的任何数据 /原始数据将不可改变,在桥接器其中一侧的更新不会导致另一侧的更新。