如果 contextIsolation = true,是否可以使用 ipcRenderer? [英] With contextIsolation = true, is it possible to use ipcRenderer?

查看:35
本文介绍了如果 contextIsolation = true,是否可以使用 ipcRenderer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的设置:

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

Step 1. Create a preload.js file with the code:

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

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

Step 2. Preload this file in your main.js via webPreferences:

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

第 3 步.在渲染器中:

Step 3. In a renderer:

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

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

Now following Electron's security guide, I wish to turn contextIsolation=true: https://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 之二.在渲染器中:

Step 3bis. In a renderer:

console.log(window.ipcRenderer);//未定义

问题:我可以在 contextIsolation=trueipcRenderer>?

Question: can I use ipcRenderer when contextIsolation=true?

推荐答案

新答案

您可以按照此处列出的设置进行操作.此设置用于 secure-electron-template 本质上,这是你可以做的:

new answer

You can follow the setup outlined here. This setup is being used in secure-electron-template Essentially, this is what you can do:

ma​​in.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));
            }
        }
    }
);

index.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;您所能做的就是从渲染器进程发送到主进程.

original

You are still able to use ipcRenderer in a renderer process with contextIsolation set to true. The contextBridge is what you want to use, although there is a current bug that is preventing from you calling ipcRenderer.on in a renderer process; all you can do is send from the renderer process to the main process.

此代码取自 secure-electron-template 一个用于 Electron 的模板牢记安全.(我是作者)

This code is taken from secure-electron-template a template for Electron built with security in mind. (I am the author)

preload.js

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

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

ma​​in.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

这篇关于如果 contextIsolation = true,是否可以使用 ipcRenderer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆