如何在反应中导入 ipcRenderer?

Vit*_*ito 10 javascript node.js reactjs webpack electron

我试图在反应应用程序中导入 ipcRenderer

import {ipcRenderer} from 'electron';
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息:未定义要求

Gh0*_*05d 10

你需要使用

const { ipcRenderer } = window.require("electron");
Run Code Online (Sandbox Code Playgroud)

否则它会尝试从 Webpack 或您使用的任何东西导入它。

您可以查看此线程以获得更好的解释:

https://github.com/electron/electron/issues/7300


Zac*_*Zac 6

您需要按照我在此评论中概述的步骤进行操作。这些步骤可确保您的电子应用程序的安全性。

主文件

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

预加载.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) => fn(...args));
            }
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

  • 在 preload.js 中,它应该是: ipcRenderer.on(channel, (event, ...args) =&gt; func(...args)); (5认同)