Reputation: 347
I want to add custom menu in menu bar in mac with electron (nodejs)
eg. we have
and I want to add filter menu
right after Electron
.
Upvotes: 8
Views: 22751
Reputation: 2184
2019 Update: Can use this component: https://www.npmjs.com/package/custom-electron-titlebar
Upvotes: 0
Reputation: 7105
There's great documentation on building native, custom application menus in the API docs here. There's lots of options and capabilities and platform differences.
For example, in your main process code you could do something like this:
const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow();
mainWindow.loadURL(path.join('file://', __dirname, 'index.html'));
setMainMenu();
});
function setMainMenu() {
const template = [
{
label: 'Filter',
submenu: [
{
label: 'Hello',
accelerator: 'Shift+CmdOrCtrl+H',
click() {
console.log('Oh, hi there!')
}
}
]
}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
That will create an application level menu with the label "Filter" and when opened will display the single menu item labeled "Hello". Clicking on it logs to the console.
Note that when you're using electron-prebuilt
, it always say "Electron" in the top left. When you compile your app as a standalone application (not running through electron-prebuilt), it'll have your app name there.
As @neonhomer pointed out, this API has to be called after the ready event of app module.
I should also add that when using Electron in development, the default Electron app will provide a default menu for you (see https://github.com/electron/electron/blob/d26e4a4abf9dfc277974c6c9678a24a5f9e4d104/default_app/main.js#L48). When you package your app, that won't be there.
Upvotes: 11
Reputation: 519
There's a small note in the API documentation: http://electron.atom.io/docs/api/menu/#menusetapplicationmenumenu
Note: This API has to be called after the ready event of app module.
Interesting that it works called directly in Windows.
Here's a simplified example:
const {app, BrowserWindow, Menu} = require('electron')
const menuTemplate = [...]
const menu = Menu.buildFromTemplate(menuTemplate)
let win
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600, })
win.loadURL(`file://${__dirname}/index.html`)
win.on('closed', () => {
win = null
})
}
app.on('ready', () => {
Menu.setApplicationMenu(menu)
createWindow()
})
app.on('window-all-closed', () => {
app.quit();
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
Upvotes: 4