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

标签 javascript google-chrome google-chrome-extension hotkeys

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

我正在看Chrome extension APIChromium文档,但尚未找到任何内容。

最佳答案

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

Chrome documentation 中包含的示例 manifest.json 内容是(稍微修改以反射(reflect)您对 Ctrl-Shift-B 的请求):

"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"
    }
  }
},

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
    }
});

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

关于javascript - 构建一个可以通过热键激活的 Chrome 扩展程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001762/

相关文章:

javascript - javascript : swapping technique, 添加随机文本

javascript - 像我五岁一样解释 : Why are dojo scripts recommended to be written in <body>?

javascript - 带笔的 Chrome canvas touchstart 无法正常工作

jquery - 为什么在 Chrome 本地加载页面时会以像素为单位显示小数?

javascript - Google Chrome 扩展程序中的自动对焦

google-chrome-extension - 如何在当前选项卡中打开 chrome 扩展程序的链接?

javascript - 使用 mongojs 添加依赖于其他查询的额外字段来查询 mongodb 中的结果

javascript - 从 native javascript 访问 Angular js Controller 变量

google-chrome - css3过滤器的一致呈现

javascript - Google Chrome 扩展程序在特定时间发出警报