2019-10-18 19:57:09 +00:00
# contextBridge
2024-08-19 21:13:55 +00:00
<!--
```YAML history
changes:
- pr-url: https://github.com/electron/electron/pull/40330
description: "`ipcRenderer` can no longer be sent over the `contextBridge` "
breaking-changes-header: behavior-changed-ipcrenderer-can-no-longer-be-sent-over-the-contextbridge
```
-->
2019-10-18 19:57:09 +00:00
> Create a safe, bi-directional, synchronous bridge across isolated contexts
Process: [Renderer ](../glossary.md#renderer-process )
An example of exposing an API to a renderer from an isolated preload script is given below:
2023-11-21 07:50:08 +00:00
```js
2019-10-18 19:57:09 +00:00
// Preload (Isolated World)
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
```
2023-11-21 07:50:08 +00:00
```js @ts -nocheck
2019-10-18 19:57:09 +00:00
// Renderer (Main World)
window.electron.doThing()
```
## Glossary
### Main World
2020-01-27 23:14:54 +00:00
The "Main World" is the JavaScript context that your main renderer code runs in. By default, the
page you load in your renderer executes code in this world.
2019-10-18 19:57:09 +00:00
### Isolated World
2021-03-22 02:01:12 +00:00
When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an
2020-01-27 23:14:54 +00:00
"Isolated World". You can read more about context isolation and what it affects in the
2022-04-18 14:09:54 +00:00
[security ](../tutorial/security.md#3-enable-context-isolation ) docs.
2019-10-18 19:57:09 +00:00
## Methods
The `contextBridge` module has the following methods:
2021-07-04 23:46:47 +00:00
### `contextBridge.exposeInMainWorld(apiKey, api)`
2019-10-18 19:57:09 +00:00
2021-11-16 04:13:18 +00:00
* `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]` .
2020-12-04 17:43:20 +00:00
* `api` any - Your API, more information on what this API can be and how it works is available below.
2019-10-18 19:57:09 +00:00
2022-09-21 18:17:10 +00:00
### `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`
* `worldId` Integer - The ID of the world to inject the API into. `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. Using 999 would expose the object for preload context. We recommend using 1000+ while creating isolated world.
* `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]` .
* `api` any - Your API, more information on what this API can be and how it works is available below.
2019-10-18 19:57:09 +00:00
## Usage
2020-12-04 17:43:20 +00:00
### API
2019-10-18 19:57:09 +00:00
2021-11-16 04:13:18 +00:00
The `api` provided to [`exposeInMainWorld` ](#contextbridgeexposeinmainworldapikey-api ) 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.
2019-10-18 19:57:09 +00:00
2020-01-27 23:14:54 +00:00
`Function` values are proxied to the other context and all other values are **copied** and **frozen** . Any data / primitives sent in
2020-12-04 17:43:20 +00:00
the API become immutable and updates on either side of the bridge do not result in an update on the other side.
2019-10-18 19:57:09 +00:00
2020-12-04 17:43:20 +00:00
An example of a complex API is shown below:
2019-10-18 19:57:09 +00:00
2023-11-21 07:50:08 +00:00
```js
2023-02-06 05:40:16 +00:00
const { contextBridge, ipcRenderer } = require('electron')
2019-10-18 19:57:09 +00:00
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
})
}
}
}
}
)
```
2022-09-21 18:17:10 +00:00
An example of `exposeInIsolatedWorld` is shown below:
2023-11-21 07:50:08 +00:00
```js
2022-09-21 18:17:10 +00:00
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInIsolatedWorld(
1004,
'electron',
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
```
2023-11-21 07:50:08 +00:00
```js @ts -nocheck
2022-09-21 18:17:10 +00:00
// Renderer (In isolated world id1004)
window.electron.doThing()
```
2019-10-18 19:57:09 +00:00
### API Functions
`Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This
results in some key limitations that we've outlined below.
#### Parameter / Error / Return Type support
2020-01-27 23:14:54 +00:00
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:
2019-10-18 19:57:09 +00:00
| Type | Complexity | Parameter Support | Return Value Support | Limitations |
| ---- | ---------- | ----------------- | -------------------- | ----------- |
2021-11-16 04:13:18 +00:00
| `string` | Simple | ✅ | ✅ | N/A |
| `number` | Simple | ✅ | ✅ | N/A |
| `boolean` | Simple | ✅ | ✅ | N/A |
2020-01-27 23:14:54 +00:00
| `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. |
2019-10-18 19:57:09 +00:00
| `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type |
2022-01-27 11:23:40 +00:00
| `Error` | Complex | ✅ | ✅ | Errors 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 ](https://github.com/electron/electron/issues/25596 ) |
2024-05-10 09:00:15 +00:00
| `Promise` | Complex | ✅ | ✅ | N/A |
2019-10-18 19:57:09 +00:00
| `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. |
| [Cloneable Types ](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ) | Simple | ✅ | ✅ | See the linked document on cloneable types |
2020-12-10 21:03:00 +00:00
| `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. |
2021-05-26 17:34:29 +00:00
| `Blob` | Complex | ✅ | ✅ | N/A |
2019-10-18 19:57:09 +00:00
| `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped |
2020-01-27 23:14:54 +00:00
If the type you care about is not in the above table, it is probably not supported.
2021-03-22 02:01:12 +00:00
2024-09-05 21:04:52 +00:00
### Exposing ipcRenderer
Attempting to send the entire `ipcRenderer` module as an object over the `contextBridge` will result in
an empty object on the receiving side of the bridge. Sending over `ipcRenderer` in full can let any
code send any message, which is a security footgun. To interact through `ipcRenderer` , provide a safe wrapper
like below:
```js
// Preload (Isolated World)
contextBridge.exposeInMainWorld('electron', {
onMyEventName: (callback) => ipcRenderer.on('MyEventName', (e, ...args) => callback(args))
})
```
```js @ts -nocheck
// Renderer (Main World)
window.electron.onMyEventName(data => { /* ... */ })
```
2021-03-22 02:01:12 +00:00
### Exposing Node Global Symbols
The `contextBridge` can be used by the preload script to give your renderer access to Node APIs.
The table of supported types described above also applies to Node APIs that you expose through `contextBridge` .
Please note that many Node APIs grant access to local system resources.
Be very cautious about which globals and APIs you expose to untrusted remote content.
2023-11-21 07:50:08 +00:00
```js
2021-03-22 02:01:12 +00:00
const { contextBridge } = require('electron')
2023-08-30 15:55:23 +00:00
const crypto = require('node:crypto')
2021-03-22 02:01:12 +00:00
contextBridge.exposeInMainWorld('nodeCrypto', {
sha256sum (data) {
const hash = crypto.createHash('sha256')
hash.update(data)
return hash.digest('hex')
}
})
```