Change Electron's menu item's status dynam

2019-07-18 05:19发布

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?

3条回答
我只想做你的唯一
2楼-- · 2019-07-18 06:04

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.

查看更多
forever°为你锁心
3楼-- · 2019-07-18 06:09

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
查看更多
做自己的国王
4楼-- · 2019-07-18 06:23

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);
});
查看更多
登录 后发表回答