在我的menu.js中的“label:'Database'”下,单击事件返回错误:ipc未定义。我想,如果这是 main.js 文件的一部分,并且如果我已经在全局范围内声明了一个 const 为 ipc,那么 JS 不应该查看上面的范围并找到 ipc 吗?
main.js:
const electron = require('electron'),
{app, Menu} = require('electron'),
Window = electron.BrowserWindow,
path = require('path'),
url = require('url'),
ipc = require('electron').ipcMain, // COMMUNICATIONS MODULE BETWEEN MAIN/RENDERER
template = require('./menu.js');
// let mainWindow
app.on('ready', () => {
// LOADS THE DEFAULT WINDOW
let first_Window = new Window({width:800, height:600, frame:false})
first_Window.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:'
}))
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
})
菜单.js:
module.exports = [
{
label: 'stuff',
submenu: [
{role: 'undo'},
{role: 'redo'},
{type: 'separator'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'pasteandmatchstyle'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'Database',
click() {
ipc.send('open_database', '')
}
},
{
label: 'View',
submenu: [
{role: 'reload'},
{role: 'forcereload'},
{role: 'toggledevtools'},
{type: 'separator'},
{role: 'resetzoom'},
{role: 'zoomin'},
{role: 'zoomout'},
{type: 'separator'},
{role: 'togglefullscreen'}
]
},
{
role: 'window',
submenu: [
{role: 'minimize'},
{role: 'close'}
]
},
{
role: 'help',
submenu: [
{
label: 'Learn More',
click () { require('electron').shell.openExternal('https://electron.atom.io') }
}
]
}
]
注意:我的菜单显示得很好。仅当我单击数据库时才会出现该错误。
最佳答案
为此,menu.js 中不需要 ipc
。它已经在运行相同的进程。我建议改用webcontents
。
在您的menu.js
中导入BrowserWindow并更改Database
下的click
函数
const { BrowserWindow } = require('electron');
label: 'Database',
click: () => {
const focusedWindow = BrowserWindow.getFocusedWindow();
focusedWindow.webContents.send('open-database');
}
然后在 main.js
中为 database
消息添加一个监听器,并打开一个新的 BrowserWindow
ipcMain.on('open-database', () => {
// open new BrowserWindow
});
关于javascript - 即使在 main 中全局分配了 ipc, Electron 菜单仍然显示单击时未定义 ipc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47190951/