contextBridge
Process: Renderer
An example of exposing an API to a renderer from an isolated preload script is given below:
window.electron.doThing()
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.
Isolated World
The contextBridge
module has the following methods:
apiKey
string - The key to inject the API ontowindow
with. The API will be accessible onwindow[apiKey]
.api
any - Your API, more information on what this API can be and how it works is available below.
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’scontextIsolation
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 ontowindow
with. The API will be accessible onwindow[apiKey]
.api
any - Your API, more information on what this API can be and how it works is available below.
The provided to 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.
Function
values are proxied to the other context and all other values are copied and frozen. 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.
An example of exposeInIsolatedWorld
is shown below:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInIsolatedWorld(
1004,
{
doThing: () => ipcRenderer.send('do-a-thing')
}
)
API Functions
Function
values that you bind through the 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
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:
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.
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')