我试图在react应用程序中导入 ipcRenderer
import {ipcRenderer} from 'electron';
但我收到此错误消息:需要未定义
我试图在react应用程序中导入 ipcRenderer
import {ipcRenderer} from 'electron';
但我收到此错误消息:需要未定义
你需要使用
const { ipcRenderer } = window.require("electron");
否则它会尝试从Webpack或您使用的任何module捆绑器导入它。
您可以查看此线程以获得更好的解释:
您需要按照我在此评论中概述的步骤进行操作。这些步骤可确保您的电子应用程序的安全性。
主文件
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);
});
});
预加载.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));
}
}
}
);
索引.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>
通过使用contextBridge我们可以解决这个问题
new BrowserWindow({
width: 1200,
height: 800,
backgroundColor: "white",
webPreferences: {
nodeIntegration: false,
worldSafeExecuteJavaScript: true,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
//example to display notification
ipcMain.on('notify', (_, message) => {
new Notification({title: 'Notification', body: message}).show();
})
预加载.js
const { ipcRenderer, contextBridge } = require('electron');
contextBridge.exposeInMainWorld('electron', {
notificationApi: {
sendNotification(message) {
ipcRenderer.send('notify', message);
}
}
})
然后在您的 reactjs 组件中使用以下代码将触发本机通知消息
electron
.notificationApi
.sendNotification('My custom message!');
如果您希望在react组件中的电子中快速尝试 IPC,这可能会有所帮助。
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log("heyyyy",arg) // prints "heyyyy ping"
})
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 配置中的任何东西,没有额外的配置。