Building desktop applications with Electron - Menu

Janez Čadež
2 min readMay 29, 2017

This tutorial assumes you know how to install and set up electron-quick-start project. You can find the tutorial here.

There are two kinds of menus in Electron applications, the first one is an application menu and second one is a context menu (the right-click menu). We will take a look at creating an application menu.

First, we need to define a template with labels, submenus and the types of menu items.

We will define new constant template, which is an array of objects. Every object will include a label, which will be displayed in the menu. The first View menu will have a submenu with three items. The first one is a ‘reload’ role, where we define a keyboard shortcut with the accelerator property. CmdOrCtrl+Y means Cmd + Y on MacOS and Ctrl + Y on Windows.

We will split two submenu items with a separator, we just declare new object with type property of ‘separator. And the third submenu item has a role of ‘togglefullscreen’.

const template = [   {      label: 'View',      submenu: [         { role: 'reload', accelerator: 'CmdOrCtrl+Y' },         { type: 'separator' },         { role: 'togglefullscreen' },      ]},{      label: 'Help',      submenu: [            {               label: 'Learn More',               click() { electron.shell.openExternal('https://electron.atom.io') }            }         ]     }]

The second menu item will have a label (menu name) of Help. Here, we also define a submenu array with one object. This object has a label of ‘Learn More’ and now we will do something different. When we click on Learn More, we will trigger a click() function which will open Electron website in a new browser window.

Once we create a template, we can set it up. First, we need to define new const Menu and assign electron.Menu to it.

const Menu = electron.Menu

Now, let’s show our menu by defining new const menu in the createWindow method and calling Menu.buildFromTemplate method where we include our defined template. Now, we can call the setApplicationMenu method and we pass the created menu constant.

const menu = Menu.buildFromTemplate(template)Menu.setApplicationMenu(menu)

You can try out your application by going to the console, navigating to electron-quick-start directory and running: electron .

--

--

Janez Čadež

JavaScript Engineer @poviolabs, Udemy instructor, open source contributor. https://devhealth.io