Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron.js multiple accelerators

Tags:

electron

Let's see this piece of code for an Electron menu template:

const menu = [
  {
    label: "foo"
    submenu: [
      {
        label: "bar",
        accelerator: "Control+B"
      {
    ]
  }
]

How do I register multiple accelerators for the same menu item?

Real world example: I want to register both F3 and Control+F for the Find in page function.

like image 897
Nekomajin42 Avatar asked Sep 07 '25 06:09

Nekomajin42


2 Answers

One way of solving this at least in the later versions of Electron is to add an additional invisible menu item, with the same function but different accelerator:

const menu = [
  {
    label: "foo"
    submenu: [
      {
        label: "bar",
        accelerator: "Control+B"
      },
      {
        label: "bar (invisible)",
        accelerator: "Control+C",
        visible: false,   
        acceleratorWorksWhenHidden: true
      },
    ]
  }
]

This will work exactly the same, but not show and with acceleratorWorksWhenHidden will still listen to the shortcut.

like image 129
ced-b Avatar answered Sep 10 '25 02:09

ced-b


The unfortunate answer as of now (Electron 5.0.7) is that you can't (natively). This is a tracked issue.

One commenter suggested this workaround:

// it's not possible to add multiple accelerators
// so need to do this the oldschool way
document.addEventListener('keydown', event => {
    if (process.platform === 'darwin' && event.metaKey && event.shiftKey) {
        if (event.keyCode === 221/* ] */) {
            nextConversation();
        }

      if (event.keyCode === 219/* [ */) {
            previousConversation();
        }
    }
});

Someone else suggested to use the electron-localshortcut module to work around this.

like image 28
pushkin Avatar answered Sep 10 '25 01:09

pushkin