javascript - Electron - 从 Menu 向渲染器发送自定义事件
问题描述
我偶然发现了一个问题,在创建 Electron 应用程序时,我在查找文档时遇到了很多问题。这是一个关于如何让自定义 Electron 菜单项与应用程序前端通信的问题/答案。
请让我知道这种帖子是否有用或是否需要详细说明某些部分。
对于我的一个应用程序,我希望我的前端在目录中显示图片。当用户单击他的右箭头键时,我想转到下一张图片。我希望这种行为由内置的Electron Menu Accelerator处理。
我已经构建了我的应用程序,将我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 - 使用 jQuery 删除更新总数据的表行
- expect - “spawn id exp5 not open”使用期望脚本进行 scp 时出错
- jquery - 我尝试将 JSON 数据从节点 js 服务器发送到 jquery 客户端,但它不起作用
- javascript - 禁用 Cors 插件如何工作
- python - (Python) 将列表中的项目转换为列表
- javascript - Angular 4: Ng2SearchPipeModule 使用这个模块进行搜索。无法在数字数据上正常工作
- css - 在scss中生成一个网格列,最后带有媒体断点粒子
- laravel - 通过 api 发送的 vuejs 表单数据在 laravel 控制器上不可见
- python - 读写列表,Python Pickle
- atom-editor - Atom 在 Wayland 上的 Ubuntu 上不起作用