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
中启用contextIsolatio
n(这是自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用于将API注入window
with.window
的密钥。The API will be accessible onAPI将可在window[apiKey]
.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 提供给exposeInMainWorld的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.api
必须是Function
、string
、number
、Array
、boolean
,或者其键为字符串且值为Function
、string
、number
、Array
、boolean
的对象,或者其他满足相同条件的嵌套对象。
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:为了完整起见,下面包含了一个类型支持表:
Type | ||||
---|---|---|---|---|
string | Simple | ✅ | ✅ | N/A |
number | Simple | ✅ | ✅ | N/A |
boolean | Simple | ✅ | ✅ | N/A |
Object | Complex | ✅ | ✅ | |
Array | Complex | ✅ | ✅ | Object typeObject 类型相同的限制 |
Error | Complex | ✅ | ✅ | |
Promise | Complex | ✅ | ✅ | N/A |
Function | Complex | ✅ | ✅ | |
Cloneable Types | Simple | ✅ | ✅ | |
Element | Complex | ✅ | ✅ | |
Blob | Complex | ✅ | ✅ | N/A |
Symbol | N/A | ❌ | ❌ |
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')
}
})