Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron menu module


May 25, 2021 Electron


Table of contents


menu class can be used to create native menus, which can be used as app menus and context menus .

This module is a module of the main process and can be called to the rendering process through the remote module.

Each menu has one or more menu items menu items and each menu item can have sub-menus.

The following example is a menu dynamically created by the remote module in a Web page (rendering process) and right-clicked:

<!-- index.html -->
<script>
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;

var menu = new Menu();
menu.append(new MenuItem({ label: 'MenuItem1', click: function() { console.log('item 1 clicked'); } }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true }));

window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
  menu.popup(remote.getCurrentWindow());
}, false);
</script>

Example, create an app menu using a template api during the rendering process:

var template = [
  {
    label: 'Edit',
    submenu: [
      {
        label: 'Undo',
        accelerator: 'CmdOrCtrl+Z',
        role: 'undo'
      },
      {
        label: 'Redo',
        accelerator: 'Shift+CmdOrCtrl+Z',
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        label: 'Cut',
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: 'Copy',
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: 'Paste',
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: 'Select All',
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      },
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        label: 'Reload',
        accelerator: 'CmdOrCtrl+R',
        click: function(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.reload();
        }
      },
      {
        label: 'Toggle Full Screen',
        accelerator: (function() {
          if (process.platform == 'darwin')
            return 'Ctrl+Command+F';
          else
            return 'F11';
        })(),
        click: function(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
      {
        label: 'Toggle Developer Tools',
        accelerator: (function() {
          if (process.platform == 'darwin')
            return 'Alt+Command+I';
          else
            return 'Ctrl+Shift+I';
        })(),
        click: function(item, focusedWindow) {
          if (focusedWindow)
            focusedWindow.toggleDevTools();
        }
      },
    ]
  },
  {
    label: 'Window',
    role: 'window',
    submenu: [
      {
        label: 'Minimize',
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      },
      {
        label: 'Close',
        accelerator: 'CmdOrCtrl+W',
        role: 'close'
      },
    ]
  },
  {
    label: 'Help',
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click: function() { require('electron').shell.openExternal('http://electron.atom.io') }
      },
    ]
  },
];

if (process.platform == 'darwin') {
  var name = require('electron').remote.app.getName();
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function() { app.quit(); }
      },
    ]
  });
  // Window menu.
  template[3].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  );
}

var menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);

Class: Menu

new Menu()

Create a new menu.

Method

菜单 class has the following methods:

  • menu Menu

Set the app menu menu on OS menu . In windows and linux, menus are set at the top of each menu .

  • action String

Send action to the app's first responder. This is used to mimic the default behavior of the Cocoa menu, and you typically only need MenuItem role .

See more of OS X's native action OS X Cocoa Event Handling Guide .

  • template Array

In general, template just an array parameter used to create MenuItem 参数 .

You can also add other things to the template element and they will become properties of the menu items that already exist.

The instance method

menu object has the following instance method

  • browserWindow BrowserWindow (optional) - null .
  • x Number (optional) - -1 by default.
  • y Number (must if x is set) - default is -1.
  • positioningItem Number (optional) OS X - Index of menu items below the specified coordinate mouse position. The default is -1.

Pop-up context menu browserWindow . You can selectively provide the x, y to set where the menu should be placed or it will default to the position of the current mouse.

  • menuItem MenuItem

Add menu items.

  • pos Integer
  • menuItem MenuItem

Add menu items at the formulation location.

Get an array of menu items.

Notes on the menu on OS X Application

Compared to windows and linux, the app menu on OS X is completely different from style, here are some considerations to make your menu items more native.

Standard menu

On OS X, there are many system-defined standard menus, such Services Windows menus. To make your app more standardized, you can set the role and then electron will recognize them and make your menu more standard:

  • window
  • help
  • services

Standard menu item behavior

OS X provides standard behavior for some menu items, such as About About xxx Hide Hide xxx and Hide Hide Others . To standardize the behavior of your menu items, you should set the role property for role items.

The name of the main menu

In OS X, no matter what label you set, the label for the first menu item of the app menu is never your app name. T o change it, you must modify the app name by Info.plist file of the app binding. For more information, refer to Out Information Property List Files .

Set up a menu (Linux Windows) for your browser window )

The browser setMenu and "setMenu" are able to set the menu to the type of a particular browser window.

The location of the menu item

When Menu.buildFromTemplate you can use position and id place menu items.

MenuItem position format is [placement]=[id] and the placement is before after endof id id is the unique ID of a menu item that already exists in the menu:

  • before - Insert before the corresponding reference id menu item. If the referenced menu item does not exist, insert it at the end of the menu.
  • after - inserted after the corresponding reference id menu item. If the referenced menu item does not exist, insert it at the end of the menu.
  • endof - logically contains the insertion at the end of the collection corresponding to the reference id menu item. If the referenced menu item does not exist, a new collection is created with the given id and the menu item is inserted.

When a dish item is inserted successfully, all unseeded menu items are inserted one by one at the back. So if you want to insert a set of menu items in the same place, you just need to specify the first location for this set of menu items.

Example

Template:

[
  {label: '4', id: '4'},
  {label: '5', id: '5'},
  {label: '1', id: '1', position: 'before=4'},
  {label: '2', id: '2'},
  {label: '3', id: '3'}
]

Menu:

- 1
- 2
- 3
- 4
- 5

Template:

[
  {label: 'a', position: 'endof=letters'},
  {label: '1', position: 'endof=numbers'},
  {label: 'b', position: 'endof=letters'},
  {label: '2', position: 'endof=numbers'},
  {label: 'c', position: 'endof=letters'},
  {label: '3', position: 'endof=numbers'}
]

Menu:

- ---
- a
- b
- c
- ---
- 1
- 2
- 3

[setMenu]: http://www.w3cschool.cn/electronmanual/electronmanual-browser-window.html