构建一个可以通过热键激活的 Chrome 扩展

Dio*_*ung 0 javascript google-chrome hotkeys google-chrome-extension

哪个 Chrome API 允许我编写可以通过非冲突热键(如Ctrl- Shift- B)或触控板手势(在 Mac 上)激活的扩展程序?

我正在查看Chrome 扩展 APIChromium文档,但还没有找到任何东西。

Mak*_*yen 5

可以使用manifest.json键添加键盘快捷键commands。您可以为通用操作、浏览器操作按钮 ( _execute_browser_action) 或页面操作按钮 ( _execute_page_action)添加键盘快捷键。

Chrome 文档中包含的示例manifest.json内容是(稍微修改以反映您对- -的请求):CtrlShiftB

"commands": {
  "toggle-feature-foo": {
    "suggested_key": {
      "default": "Ctrl+Shift+B",
      "mac": "Command+Shift+B"
    },
    "description": "Toggle feature foo"
  },
  "_execute_browser_action": {
    "suggested_key": {
      "windows": "Ctrl+Shift+Y",
      "mac": "Command+Shift+Y",
      "chromeos": "Ctrl+Shift+U",
      "linux": "Ctrl+Shift+J"
    }
  },
  "_execute_page_action": {
    "suggested_key": {
      "default": "Ctrl+Shift+E",
      "windows": "Alt+Shift+P",
      "mac": "Alt+Shift+P"
    }
  }
},
Run Code Online (Sandbox Code Playgroud)

toggle-feature-foo是通用的。您可以将 *manifest.json" 键更改为您想要的。它作为参数传递给您的chrome.commands.onCommand侦听器。

在您的后台脚本中,您可以拥有(从同一来源修改):

chrome.commands.onCommand.addListener(function(command) {
    console.log('Command:', command);
    if(command === 'toggle-feature-foo') {
        //Code for toggle-feature-foo
    }
});
Run Code Online (Sandbox Code Playgroud)

除非 Mac 触控板手势也生成键盘按键序列,否则无法轻松捕捉此类手势。您也许能够编写一个这样做的内容脚本。但是,如果您必须使用内容脚本来执行此操作,那么仅启用该功能就可能对每个网页造成重大负担。