docs: add document on contextIsolation (#23474)
* docs: add document on contextIsolation * fix lint * chore: link ctx isolation doc from security doc
This commit is contained in:
parent
653c36b8c9
commit
cf635c5fac
2 changed files with 73 additions and 44 deletions
|
@ -239,51 +239,10 @@ to enable this behavior.
|
|||
Even when you use `nodeIntegration: false` to enforce strong isolation and
|
||||
prevent the use of Node primitives, `contextIsolation` must also be used.
|
||||
|
||||
### Why?
|
||||
### Why & How?
|
||||
|
||||
Context isolation allows each of the scripts running in the renderer to make
|
||||
changes to its JavaScript environment without worrying about conflicting with
|
||||
the scripts in the Electron API or the preload script.
|
||||
|
||||
While still an experimental Electron feature, context isolation adds an
|
||||
additional layer of security. It creates a new JavaScript world for Electron
|
||||
APIs and preload scripts, which mitigates so-called "Prototype Pollution" attacks.
|
||||
|
||||
At the same time, preload scripts still have access to the `document` and
|
||||
`window` objects. In other words, you're getting a decent return on a likely
|
||||
very small investment.
|
||||
|
||||
### How?
|
||||
|
||||
```js
|
||||
// Main process
|
||||
const mainWindow = new BrowserWindow({
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
preload: path.join(app.getAppPath(), 'preload.js')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
```js
|
||||
// Preload script
|
||||
|
||||
// Set a variable in the page before it loads
|
||||
webFrame.executeJavaScript('window.foo = "foo";')
|
||||
|
||||
// The loaded page will not be able to access this, it is only available
|
||||
// in this context
|
||||
window.bar = 'bar'
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Will log out 'undefined' since window.foo is only available in the main
|
||||
// context
|
||||
console.log(window.foo)
|
||||
|
||||
// Will log out 'bar' since window.bar is available in this context
|
||||
console.log(window.bar)
|
||||
})
|
||||
```
|
||||
For more information on what `contextIsolation` is and how to enable it please
|
||||
see our dedicated [Context Isolation](context-isolation.md) document.
|
||||
|
||||
|
||||
## 4) Handle Session Permission Requests From Remote Content
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue