How to programmatically assign a keyboard shortcut to open an Edge Extension?

78 Views Asked by At

I'm trying to program an Edge extension, and I would like the extension to open when I press a keyboard shortcut (for now, I want to use Ctrl-B). I found a way to assign a keyboard shortcut after I install the extension, by going to edge://extensions/shortcuts and then using the Microsoft GUI to assign the keyboard shortcut. But, I want to do this via code. I've tried the following snippets in manifest.json and popup.js, but they don't work. Thanks in advance for your help.

.....
  "commands": {
      "openExtension": {
          "suggested_key": {
              "default": "Ctrl+B"
          },
          "description": "My description"
      }
  }
.....


....
chrome.commands.onCommand.addListener(function(command) {
    if (command === 'openExtension') {
        chrome.runtime.sendMessage({action: 'openExtension'});
    }
});
....
1

There are 1 best solutions below

2
Yu Zhou On

It seems that we only need to use _execute_action to define the shortcut to open the extension. For example, you can add below code in manifest.json:

"commands": {
      "_execute_action": {
        "suggested_key": {
          "default": "Ctrl+Shift+5",
          "mac": "Command+Shift+5"
        }
      }
  },
"permissions": [
      "activeTab"
    ]

Then you'll find it works and automatically shows in edge://extensions/shortcuts.

Please note that not all keyboards combinations will work, I suggest you use Ctrl+Shift+[0..9]. You can also refer to this doc:

Keyboard shortcut suggestions for global commands are limited to Ctrl+Shift+[0..9]. This is a protective measure to minimize the risk of overriding shortcuts in other applications.