首页 > 解决方案 > 如果 contextIsolation = true,是否可以使用 ipcRenderer?

问题描述

这是我的设置:

步骤 1. 使用代码创建一个 preload.js 文件:

window.ipcRenderer = require('electron').ipcRenderer;

步骤 2. 通过 webPreferences 在 main.js 中预加载此文件:

  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });

步骤 3. 在渲染器中:

console.log(window.ipcRenderer); // Works!

现在按照 Electron 的安全指南,我想转contextIsolation=truehttps ://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content

步骤 2 之二。

  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });

步骤 3 之二。在渲染器中:

console.log(window.ipcRenderer); // undefined

问题:我可以在什么时候使用ipcRenderercontextIsolation=true吗?

标签: securityelectron

解决方案


新答案

您可以按照此处列出的设置进行操作。本质上,此设置正在使用中secure-electron-template,这就是您可以执行的操作:

main.js

const {
  app,
  BrowserWindow,
  ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

async function createWindow() {

  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // is default value after Electron v5
      contextIsolation: true, // protect against prototype pollution
      enableRemoteModule: false, // turn off remote
      preload: path.join(__dirname, "preload.js") // use a preload script
    }
  });

  // Load app
  win.loadFile(path.join(__dirname, "dist/index.html"));

  // rest of code..
}

app.on("ready", createWindow);

ipcMain.on("toMain", (event, args) => {
  fs.readFile("path/to/file", (error, data) => {
    // Do something with file contents

    // Send result back to renderer process
    win.webContents.send("fromMain", responseObj);
  });
});

preload.js

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

索引.html

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="utf-8"/>
    <title>Title</title>
</head>
<body>
    <script>
        window.api.receive("fromMain", (data) => {
            console.log(`Received ${data} from main process`);
        });
        window.api.send("toMain", "some data");
    </script>
</body>
</html>

原来的

仍然可以在 contextIsolation 设置为 true 的渲染器进程中使用 ipcRenderer。contextBridge是您想要使用的,尽管当前存在一个阻止您在渲染器进程中调用 ipcRenderer.on 的错误;您所能做的就是从渲染器进程发送到主进程。

此代码取自secure-electron-template ,这是一个考虑到安全性而构建的Electron 模板。(我是作者)

preload.js

const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld(
    "electron",
    {
        ipcRenderer: ipcRenderer
    }
);

main.js

let win;

async function createWindow() {

  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      nodeIntegrationInWorker: false,
      nodeIntegrationInSubFrames: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: path.join(__dirname, "preload.js")
    }
  });
}

一些 renderer.js 文件

window.electron.ipcRenderer


推荐阅读