'How to make contextBridge work even if contextisolation is turned off
I some of my code requires contextIsolation turned on and my preload.js looks like this:
const { contextBridge } = require("electron");
const { ipcRenderer } = require("electron/renderer");
const API = {
window: {
close: () => ipcRenderer.send("app/close"),
minimize: () => ipcRenderer.send("app/minimize"),
}
}
contextBridge.exposeInMainWorld("app", API);
and everytime I launch the app it sends this error:
Uncaught Error: contextBridge API can only be used when contextIsolation is enabled
at node:electron/js2c/renderer_init:45:277
at Object.exposeInMainWorld (node:electron/js2c/renderer_init:45:359)
at preload.js:11:15
Edit: Here is the script that is supposed to be interacting with the preload script:
const { ipcRenderer } = require("electron/renderer");
const MINUS = document.getElementById("minimizeApp");
const CLOSE = document.getElementById("closeApp");
MINUS.addEventListener("click", minimizeApp);
CLOSE.addEventListener("click", closeApp);
function closeApp() {
app.window.close();
}
function minimizeApp() {
app.window.minimize();
}
this is imported via the <script> tag.
Thanks in advance.
Solution 1:[1]
The point of that API is to bridge a gap between otherwise two completely isolated places. If you're not isolating them you have no reason to use it hence the error message.
With context isolation
As the preload script will be executed in a different context, you need the Context Bridge API to expose your API to the renderer process:
contextBridge.exposeInMainWorld('MY_API', {
getAnswer() {
return 42;
}
});
Without context isolation
Both the preload script and the renderer process share the same context. So in the preload script you can simply attach your API directly to the window object. That window will be the same as the one in the renderer process:
// preload script
window.MY_API = {
getAnswer() {
return 42;
}
}
? i.e. no need to use the Context Bridge API here ;)
In any case MY_API is available from the window object in your renderer process:
<!-- renderer process -->
<body>
<script>
alert(window.MY_API.getAnswer());
</script>
</body>
Solution 2:[2]
Check the docs of electron. Turning contextIsolation off is a no-no for newer versions of electron. What you actually want is to expose MY_API through contextBridge and setup an ipcRenderer to signal processes back and forth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | George Makroglou |
