Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Fabio Marzocca Avatar asked Dec 11 '17 16:12

Fabio Marzocca


2 Answers

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
like image 134
Fabio Marzocca Avatar answered Nov 17 '22 00:11

Fabio Marzocca


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.

like image 1
OJ Kwon Avatar answered Nov 17 '22 01:11

OJ Kwon