This post will show you how to set up menus in Electron and Mac OS X.
Get started
npm init
Let’s set up a basic simple Electron app.
Start with
$ npm init -y |
- Set the
mainentry point tosrc/index.js. - Set the
startnpm script to beelectron ..
Install Electron
Then install electron with
$ npm install --save-dev electron-prebuilt |
index.js
Create an src/index.js file and put the following content in:
const electron = require('electron'); |
Run npm start and doublecheck that everything works – you should see a blank window open and the Mac OS X menu is the default Electron menu.
If you need help with that part, check out my tutorial on getting started with Electron.
Set a custom menu
Override the Default Electron Development Menu
First pull the Menu class from electron:
const Menu = electron.Menu; |
Then use the buildFromTemplate method to generate the menu and setApplicationMenu to set it.
Here is the full code:
const electron = require('electron'); |
Run the app and check that the default menu is no more.
Define some menu items
At the moment, our menu is empty. (Also you can’t set the first Menu name to anything else than Electron – you need to package the app for another name to appear)
- Let’s add an about menu item.
const menuTemplate = [ |
Run the app and observe how a click writes to the console.
- Let’s add a Quit Menu Item.
const menuTemplate = [ |
Run the app and doublecheck that the Quit button actually quits the app.
- Let’s add a separator
You might have noticed that something is missing. Let’s add an horizontal line in between About and Quit with { type: 'separator' }
const menuTemplate = [ |
Run the app and notice the difference.
What’s next ?
Now that you know the basics of setting up a custom menu for your app, you should have no problem scrolling through the docs.
Here are a few things you can try:
- Try to use the
acceleratorproperty to link menu items with Application Shortcuts. - Set a default
rolefor the click action. Check the list of roles here. - Create a submenu with the
submenuproperty.