[英]Electron menu keeps saying that ipc is not defined when clicked even when the ipc is assigned globally in main
在我的menu.js中“標簽:'數據庫”下,單擊事件返回錯誤:ipc未定義。 我以為如果這是main.js文件的一部分,並且如果我已經有一個全局聲明為ipc的const,那么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)
})
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
});
由於Menu
是主要的過程類,因此您不必使用ipc通信來執行諸如打開新的BrowserWindow
(顯然是您想要的)之類的事情。
const {BrowserWindow} = require('electron')
module.exports = [
{
label: 'Database',
click (menuItem, browserWindow, event) {
let win = new BrowserWindow()
win.loadURL('https://electron.atom.io/docs/api/menu-item/')
}
}
]
應該在您的模板中就足夠了
請注意,如果您打算與窗口的渲染器進程進行通信,則browserWindow
參數附帶的click
回調使您可以訪問包含菜單項的窗口(請參見文檔中的MenuItem
click
屬性)。 然后,您可以執行executeJavascript
或使用此參數send
ipc消息發送到渲染器進程。
還要注意,盡管事實上在需要此模板的其他文件中已經定義了BrowserWindow
(或ipc
或其他內容),但您仍必須重新定義它。 需求/導入/包含鏈在兩個方向上不起作用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.