Search code examples
javascriptnode.jsmenuelectronpackager

Why does a packaged Electron app fail due to Menu.getApplicationMenu() returning null while running it with electron . is fine?


I get a strange error when running a packaged Electron app on Windows 10. enter image description here

When I press Ok on this error, the application boots up, but without a menu. If I run the same application using electron . it works perfectly, it has a menu.

The error occurs here:

var filemenu = Menu.getApplicationMenu().items[0].submenu;
filemenu.items[0].visible = false;
filemenu.append(new MenuItem({ label: 'Build Project', click: function () { buildProject(); } }));

I'm trying to edit the default File menu and add a "Build Project" item.

This is my first attempt to package an Electron app so I welcome any feedback as to what went wrong?


Solution

  • It seems that the default menu is not added to the app when in production.

    The solution is to check if you are in development:

    https://www.npmjs.com/package/electron-is-dev

    // Check if we are in development
    var isDev = require('electron-is-dev');
    

    If in production, you have to construct the menu from scratch.

    if(isDev){
        // In development
        // modify existing menu
    }else{
        // In production
        // construct menu from scratch
        var template = [
                {
                    label: "File",
                    submenu: [
                        {
                            label: "Exit",
                            click: function () { quit(); }
                        }
                    ]
                },
                {
                    label: "Project",
                    submenu: [
                        {
                            label: "Delete",
                            click: function () { deleteProject(); }
                        },
                        {
                            label: "Build",
                            click: function () { buildProject(); }
                        }
                    ]
                }
            ];        
        // build menu from template
        var menu = Menu.buildFromTemplate(template);    
        // set menu for main window
        mainWindow.setMenu(menu);
    };