好吧,我想我明白了……
我可以使用官方文档here 中描述的模式在我的preload.js 中创建一个API,然后应用程序菜单可以调用该API 以向渲染进程发送消息。所以在preload.js 我有:
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
loadSomeFile: (callback) => ipcRenderer.on('load-some-file', callback),
})
然后我这样定义我的菜单:
const { app, Menu, MenuItem, ipcMain } = require('electron');
module.exports = (window) => {
return Menu.buildFromTemplate([
{
label: 'File',
submenu: [
{
label: 'About',
},
{
label: 'Preferences',
},
{
type: 'separator'
},
{
label: 'Load Some File',
click() {
window.webContents.send('load-some-file', 1);
}
},
{
type: 'separator'
},
{
label: 'Exit',
click() {
app.quit()
}
}
]
},
])
}
在我的main.js 我有:
const { app, BrowserWindow, Menu, } = require('electron');
const path = require("path");
const mainMenu = require("./app/main-menu");
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true
}
});
win.loadURL("http://localhost:8080");
return win;
}
app.whenReady().then(() => {
const win = createWindow();
Menu.setApplicationMenu(mainMenu(win));
});
我在 React/Redux/MUI 前端代码中已有的大部分内容可以保持不变。但我需要从前端的 window 对象访问 api,并监听来自主进程的事件(如来自应用程序菜单)。
window.api.loadSomeFile((event, data) => {
console.log(data);
});
经过测试,效果很好。我的代码几乎没有实际更改。