Skip to main content

contextBridge

Create a safe, bi-directional, synchronous bridge across isolated contexts在孤立的上下文中创建一个安全、双向、同步的桥接

Process:进程:Renderer

An example of exposing an API to a renderer from an isolated preload script is given below:下面给出了一个从隔离的预加载脚本向渲染器公开API的示例:

// Preload (Isolated World)
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
// Renderer (Main World)

window.electron.doThing()

Glossary术语汇编

Main World主世界

The "Main World" is the JavaScript context that your main renderer code runs in. “主世界”是您的主要渲染器代码运行的JavaScript上下文。By default, the page you load in your renderer executes code in this world.默认情况下,您在渲染器中加载的页面在这个世界中执行代码。

Isolated World孤立世界

When contextIsolation is enabled in your webPreferences (this is the default behavior since Electron 12.0.0), your preload scripts run in an "Isolated World". 当在webPreferences中启用contextIsolation(这是自Electron 12.0.0以来的默认行为)时,预加载脚本将在“孤立世界”中运行。You can read more about context isolation and what it affects in the security docs.您可以在安全文档中阅读更多关于上下文隔离及其影响的内容。

Methods方法

The contextBridge module has the following methods:contextBridge模块具有以下方法:

contextBridge.exposeInMainWorld(apiKey, api)

  • apiKey string - The key to inject the API onto window with. 用于将API注入window的密钥。The API will be accessible on window[apiKey].API将可在window[apiKey]上访问。
  • api any - Your API, more information on what this API can be and how it works is available below.您的API,关于此API可以是什么以及它是如何工作的更多信息,请参阅下文。

Usage用法

API

The api provided to exposeInMainWorld must be a Function, string, number, Array,boolean, or an object whose keys are strings and values are a Function,string, number, Array,boolean, or another nested object that meets the same conditions.提供给exposeInMainWorldapi必须是FunctionstringnumberArrayboolean,或者其键为字符串且值为FunctionstringnumberArrayboolean的对象,或者其他满足相同条件的嵌套对象。

Function values are proxied to the other context and all other values are copied and frozen. Function值被代理到其他上下文,并且所有其他值都被复制冻结Any data / primitives sent in the API become immutable and updates on either side of the bridge do not result in an update on the other side.在API中发送的任何数据/基元都将变为不可变的,并且桥的任何一侧的更新都不会导致另一侧的更新。

An example of a complex API is shown below:复杂API的示例如下所示:

const { contextBridge } = require('electron')

contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing'),
myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))],
anAsyncFunction: async () => 123,
data: {
myFlags: ['a', 'b', 'c'],
bootTime: 1234
},
nestedAPI: {
evenDeeper: {
youCanDoThisAsMuchAsYouWant: {
fn: () => ({
returnData: 123
})
}
}
}
}
)

API Functions

Function values that you bind through the contextBridge are proxied through Electron to ensure that contexts remain isolated. 通过contextBridge绑定的Function值通过Electron代理,以确保上下文保持隔离。This results in some key limitations that we've outlined below.这导致了我们在下面概述的一些关键限制。

Parameter / Error / Return Type support

Because parameters, errors and return values are copied when they are sent over the bridge, there are only certain types that can be used. 由于参数、错误和返回值在网桥上发送时会被复制,因此只能使用某些类型。At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. 在高层,如果您想要使用的类型可以被序列化和反序列化到同一个对象中,那么它就可以工作了。A table of type support has been included below for completeness:为了完整起见,下面包含了一个类型支持表:

TypeComplexity复杂性Parameter Support参数支持Return Value Support回报价值支持Limitations局限性
stringSimpleN/A
numberSimpleN/A
booleanSimpleN/A
ObjectComplexKeys must be supported using only "Simple" types in this table. 必须仅使用此表中的“Simple”类型来支持键。Values must be supported in this table. Prototype modifications are dropped. 此表中必须支持值。原型修改被删除。Sending custom classes will copy values but not the prototype.发送自定义类将复制值,但不会复制原型。
ArrayComplexSame limitations as the Object typeObject类型相同的限制
ErrorComplexErrors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context, and any custom properties on the Error object will be lost抛出的错误也会被复制,这可能导致错误的消息和堆栈跟踪由于抛出在不同的上下文中而略有更改,并且error对象上的任何自定义属性都将丢失
PromiseComplexN/A
FunctionComplexPrototype modifications are dropped. 原型修改被删除。 Sending classes or constructors will not work.发送类或构造函数将不起作用。
Cloneable TypesSimpleSee the linked document on cloneable types请参阅关于可克隆类型的链接文档
ElementComplexPrototype modifications are dropped. 原型修改被删除。Sending custom elements will not work.发送自定义元素将不起作用。
BlobComplexN/A
SymbolN/ASymbols cannot be copied across contexts so they are dropped符号无法跨上下文复制,因此会被删除

If the type you care about is not in the above table, it is probably not supported.如果您关心的类型不在上表中,则可能不支持它。

Exposing Node Global Symbols公开节点全局符号

The contextBridge can be used by the preload script to give your renderer access to Node APIs. 预加载脚本可以使用contextBridge为渲染器提供对节点API的访问权限。The table of supported types described above also applies to Node APIs that you expose through contextBridge. 上面描述的受支持类型表也适用于您通过contextBridge公开的Node API。Please note that many Node APIs grant access to local system resources. 请注意,许多节点API都允许访问本地系统资源。Be very cautious about which globals and APIs you expose to untrusted remote content.对于向不受信任的远程内容公开哪些全局变量和API,要非常谨慎。

const { contextBridge } = require('electron')
const crypto = require('crypto')
contextBridge.exposeInMainWorld('nodeCrypto', {
sha256sum (data) {
const hash = crypto.createHash('sha256')
hash.update(data)
return hash.digest('hex')
}
})