我尝试在react应用程序中导入ipcRenderer
import {ipcRenderer} from 'electron';但我得到了以下错误消息:未定义要求
发布于 2018-02-28 16:28:05
你需要用
const { ipcRenderer } = window.require("electron");否则,它将尝试从Webpack或任何您使用的模块绑定器导入它。
您可以查看这个线程以获得更好的解释:
发布于 2020-01-18 00:05:25
您将希望遵循我在这句话中概述的步骤。这些步骤确保您的电子应用程序的安全。
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) => fn(...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>发布于 2020-09-29 16:50:21
如果您希望快速尝试在一个反应组件的电子IPC,这可能会有所帮助。
main.js
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log("heyyyy",arg) // prints "heyyyy ping"
})App.js
import React from 'react';
import './App.css';
const { ipcRenderer } = window.require('electron');
function App() {
return (
<div className="App">
<button onClick={()=>{
ipcRenderer.send('asynchronous-message', 'ping')
}}>Com</button>
</div>
);
}
export default App;输出:

别忘了在做完修改后重新运行这个应用程序。
没有添加preload.js,没有改变webpack配置中的任何东西,没有额外的配置。
https://stackoverflow.com/questions/48148021
复制相似问题