简体   繁体   中英

Custom Menu Not Showing in Electron - MacOS

I am just getting started with Electron and following the Getting Started guide. After running the script to launch an app with custom menu, the app's menu still shows Electron rather than my custom name 'File'. I tried the suggestions in similar questions in particular putting Menu.setApplicationMenu() in the function createWindow() but this still doesn't work.

Here is the code:

// main.js

const electron = require('electron');
const url = require('url'); 
const path = require('path');

const {app, BrowserWindow, Menu} = electron;

let mainWindow;

function createWindow() {
  // Create new window
  mainWindow = new BrowserWindow({width: 900, height: 550});

  // Load html into window
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'mainWindow.html'),
    protocol: 'file:',
    slashes: true
  }));

  // Create menu template
  const mainMenuTemplate = [
    {
        label: 'File',
        submenu: [
        {
            role: 'quit'
        }
        ]
    }
  ];

  // Insert menu
  Menu.setApplicationMenu(Menu.buildFromTemplate(mainMenuTemplate));
}

// Listen for app to be ready
app.on('ready', createWindow);

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>ShoppingList</title> 
</head>
<body>
  <h1>ShoppingList</h1>
</body>
</html>

Any idea what I am missing?

here is a working example for creating a menu for mac:

    let template = [
  {
    label: 'My app title',
    submenu: [{
        label: 'menu command name',
        click: function() {
          //execute command
        }
      },
      {
        label: 'quit app command name',
        accelerator: 'CmdOrCtrl+Q',
        click: function() {
          //quit command execution 
        }
      }
    ]
  },
  {
    label: 'edit',
    submenu: [{
        label: 'undo',
        accelerator: 'CmdOrCtrl+Z',
        selector: 'undo:'
      },
      {
        label: 'redo',
        accelerator: 'Shift+CmdOrCtrl+Z',
        selector: 'redo:'
      },
      {
        type: 'separator'
      },
      {
        label: 'cut',
        accelerator: 'CmdOrCtrl+X',
        selector: 'cut:'
      },
      {
        label: 'copy',
        accelerator: 'CmdOrCtrl+C',
        selector: 'copy:'
      },
      {
        label: 'paste',
        accelerator: 'CmdOrCtrl+V',
        selector: 'paste:'
      },
      {
        label: 'selectAll',
        accelerator: 'CmdOrCtrl+A',
        selector: 'selectAll:'
      }]
  }
];

let osxMenu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(osxMenu);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM