我偶然发现了一个问题,在创建Electron应用程序时,我在查找文档时遇到了很多问题。这是有关如何使自定义 Electron 菜单项与应用程序前端进行通信的问题/解答。
请让我知道此类帖子是否有用或是否需要详细说明。
对于我的一个应用程序,我希望前端在目录中显示图片。当用户单击他的右箭头键时,我要转到下一张图片。我希望通过内置的 Electron 菜单加速器处理此行为。
我已经构建了将我的main.js
与菜单模板分开的应用,如下所示:
app
├── main.js
├── renderer.js
├── index.html
├── templates
├── menu.js => uses objects from picture.js and about.js to build & return a menu
├── picture.js
├── about.js
├── ... (rest of files)
我的picture.js看起来像这样:const picture = {
label: 'Picture',
role: 'help',
submenu: [
{
label: 'Previous',
accelerator: 'Left',
click: function() {
// this needs to be figured out
},
},
{
label: 'Next',
accelerator: 'Right',
click: function() {
// this needs to be figured out
},
}
],
}
exports.picture = picture;
我的直觉告诉我要摆弄ipcMain,但是这种方法行不通。我收到很多消息,说ipc is not defined
或the method send of undefined
无法正常工作。这是我设法解决问题的方法:
最佳答案
我们知道什么:为了在Menu和前端之间进行通信,我们需要在main.js
中创建一个事件。正是main.js
会将事件发送到renderer.js
。
我们在搜索时发现的内容:可以使用webContents.send将消息从主进程发送到渲染器进程
如何应用:我们需要调用“app”(应用程序对象)并“发出”事件。这就是为什么我们必须将“图片”对象更改为带有一个参数的函数:app。
const fileMenu = () => {
return {
label: 'Picture',
role: 'help',
submenu: [
{
label: 'Previous',
accelerator: 'Left',
click: () => app.emit('prevPicture'),
},
{
label: 'Next',
accelerator: 'Right',
click: () => app.emit('nextPicture'),
}
],
}
}
exports.fileMenu = fileMenu;
然后我们只需要在main中添加参数:// LOTS OF CODE ...
// mainWindow is the name of the Electron BrowserWindow object that holds our menu and app
app.on('ready', function() {
const template = new AppMenu([fileMenu(app), editMenu, windowMenu, aboutMenu]).getTemplate();
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
createWindow();
});
// OTHER CODE ...
app.on('prevPicture', () => {mainWindow.webContents.send('prevPicture');});
app.on('nextPicture', () => {mainWindow.webContents.send('nextPicture');});
// REST OF CODE ...
这使我们可以在ipc.on('prevPicture', () => doWhatever)
文件中使用简单的renderer.js
并创建将影响Electron前端的自定义键盘快捷键。
关于javascript - Electron -将自定义事件从菜单发送到渲染器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65293282/