Fabio Marzocca
Fabio Marzocca

Reputation: 1677

Change Electron's menu item's status dynamically

Like in any standard native application, also my electron's application needs to change the status (enabled/dsabled) of several menu item, based on live usage results.

I am setting up my menu in main.js:

function createWindow () {
...
...
  require('./menu/mainmenu');
}

The MenuItem I need to change is defined in mainmenu:

{ label: "Show Colors",  
        accelerator: 'CmdOrCtrl+1', 
        enabled: getStatus(),
        click() {getWebviewWebContents().send('switchToColors');} 
 },

where getStatus() is function returning false or true.

All this is not working in Electron, as the menu is created at application start and it can't be modified at all. I believe this is a serious lack, as dynamic menu items are very common (i.e.: menu checkboxes, enabled/disabled, etc).

Is there any workaround for this?

Upvotes: 15

Views: 10405

Answers (3)

Shihab
Shihab

Reputation: 2679

Here is my solution:

main.js (main process)

const menuTemplate = [{
    label: 'Options',
    submenu: [
       {
         label: 'Config',
         enabled: false,
         click() { //do stuff }
       }
    ]
}];

// Enable menu items when user login. Fetching value from renderer process
ipcMain.on('logged-in', (event, args) => {
    if (args !== true) {
        return;
    }

    // Modify menu item status
    menuTemplate[0].submenu[0].enabled = true;

    // Rebuild menu
    const menu = Menu.buildFromTemplate(menuTemplate);
    Menu.setApplicationMenu(menu);
});

Upvotes: 1

Fabio Marzocca
Fabio Marzocca

Reputation: 1677

I have fixed this by setting an Id to the menu item,

{ label: "Show Colors",  
        id: 'color-scale',
        accelerator: 'CmdOrCtrl+1', 
        enabled: getStatus(),
        click() {getWebviewWebContents().send('switchToColors');} 
 },

and getting the menu item with:

myItem = menu.getMenuItemById('color-scale')

Then, when I need to enable/disable it programmatically, I am using:

myItem.enabled = true

or

myItem.enabled = false

Upvotes: 37

OJ Kwon
OJ Kwon

Reputation: 4641

The only workaround so far I aware and using is reconstruct whole menu each time menuitem changes. This is not very ergonomics friendly, but works suffeciently enough and doesn't cause lot of overhead.

Upvotes: 1

Related Questions