error 3a contextbridge api can only be used when contextisolation is enabled

Solutions on MaxInterview for error 3a contextbridge api can only be used when contextisolation is enabled by the best coders in the world

showing results for - "error 3a contextbridge api can only be used when contextisolation is enabled"
Marvin
28 Feb 2016
1<!doctype html>
2<html lang="en-US">
3<head>
4    <meta charset="utf-8"/>
5    <title>Title</title>
6</head>
7<body>
8    <script>
9        window.api.receive("fromMain", (data) => {
10            console.log(`Received ${data} from main process`);
11        });
12        window.api.send("toMain", "some data");
13    </script>
14</body>
15</html>
16
Anna
03 Oct 2017
1const {
2  app,
3  BrowserWindow,
4  ipcMain
5} = require("electron");
6const path = require("path");
7const fs = require("fs");
8
9// Keep a global reference of the window object, if you don't, the window will
10// be closed automatically when the JavaScript object is garbage collected.
11let win;
12
13async function createWindow() {
14
15  // Create the browser window.
16  win = new BrowserWindow({
17    width: 800,
18    height: 600,
19    webPreferences: {
20      nodeIntegration: false, // is default value after Electron v5
21      contextIsolation: true, // protect against prototype pollution
22      enableRemoteModule: false, // turn off remote
23      preload: path.join(__dirname, "preload.js") // use a preload script
24    }
25  });
26
27  // Load app
28  win.loadFile(path.join(__dirname, "dist/index.html"));
29
30  // rest of code..
31}
32
33app.on("ready", createWindow);
34
35ipcMain.on("toMain", (event, args) => {
36  fs.readFile("path/to/file", (error, data) => {
37    // Do something with file contents
38
39    // Send result back to renderer process
40    win.webContents.send("fromMain", responseObj);
41  });
42});
43
Ali
20 Apr 2017
1const {
2    contextBridge,
3    ipcRenderer
4} = require("electron");
5
6// Expose protected methods that allow the renderer process to use
7// the ipcRenderer without exposing the entire object
8contextBridge.exposeInMainWorld(
9    "api", {
10        send: (channel, data) => {
11            // whitelist channels
12            let validChannels = ["toMain"];
13            if (validChannels.includes(channel)) {
14                ipcRenderer.send(channel, data);
15            }
16        },
17        receive: (channel, func) => {
18            let validChannels = ["fromMain"];
19            if (validChannels.includes(channel)) {
20                // Deliberately strip event as it includes `sender` 
21                ipcRenderer.on(channel, (event, ...args) => func(...args));
22            }
23        }
24    }
25);
26