Local data and native APIs

Add an application menu

Create a cross-platform menu with native roles and send a narrow New Note event to the renderer.

12 minute lesson

~~~

Electron menus use templates. Built-in roles follow operating-system labels, placement, and common keyboard behavior.

const { Menu } = require('electron')

function installMenu(win) {
  const template = [
    ...(process.platform === 'darwin' ? [{ role: 'appMenu' }] : []),
    {
      label: 'File',
      submenu: [
        {
          label: 'New Note',
          accelerator: 'CmdOrCtrl+N',
          click: () => {
            if (!win.isDestroyed()) {
              win.webContents.send('notes:new')
            }
          }
        },
        { role: 'quit' }
      ]
    },
    { role: 'editMenu' },
    { role: 'viewMenu' },
    { role: 'windowMenu' }
  ]

  Menu.setApplicationMenu(Menu.buildFromTemplate(template))
}

Call installMenu(win) after creating the window.

The menu runs in the main process. It sends one fixed event to the known renderer, and preload removes Electron’s event object before calling createNote().

The appMenu role provides the conventional first macOS menu. Other roles provide platform shortcuts and labels better than handwritten copies.

Test the menu with a mouse and CmdOrCtrl+N. Close the window and trigger the command if the platform still exposes the menu. The destroyed-window guard should prevent a send to dead web contents.

If a menu action performs privileged work, do it in the main process or call the same validated function as IPC. Do not create a second unchecked implementation just for the menu.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →