Context Isolation
What is it?
Context Isolation is a feature that ensures that both your preload
scripts and Electron's internal logic run in a separate context to the website you load in a webContents
. This is important for security purposes as it helps prevent the website from accessing Electron internals or the powerful APIs your preload script has access to.
This means that the window
object that your preload script has access to is actually a different object than the website would have access to. For example, if you set window.hello = 'wave'
in your preload script and context isolation is enabled, window.hello
will be undefined if the website tries to access it.
Context isolation has been enabled by default since Electron 12, and it is a recommended security setting for all applications.
Migration
Without context isolation, I used to provide APIs from my preload script using
window.X = apiObject
. Now what?
Before: context isolation disabled
Exposing APIs from your preload script to a loaded website in the renderer process is a common use-case. With context isolation disabled, your preload script would share a common global window
object with the renderer. You could then attach arbitrary properties to a preload script:
// preload with contextIsolation disabled
window.myAPI = {
doAThing: () => {}
}
The doAThing()
function could then be used directly in the renderer process:
// use the exposed API in the renderer
window.myAPI.doAThing()