回答

8

使用chrome.commands API可以覆盖快捷方式。扩展可以表明,在manifest文件默认的快捷方式(例如,按Ctrl + d。),但用户可以自由在chrome://extensions/覆盖此,如下所示:

Keyboard Shortcuts - Extensions and Apps

使用

此API仍在开发中,仅在BetaDev频道可用,而Canary构建More info。它可能适用于Chrome 24开始的所有人。

如果要在Chrome 23或更低版本中测试API,请将“实验”权限添加到清单文件中,并使用chrome.experimental.commands而不是chrome.commands。同时访问chrome://flags/并启用“实验性扩展API”,或使用--enable-experimental-extension-apis标志启动Chrome。

manifest.json

{ 
    "name": "Remap shortcut", 
    "version": "1", 
    "manifest_version": 2, 
    "background": { 
     "scripts": ["background.js"] 
    }, 
    "permissions": [ 
     "tabs" 
    ], 
    "commands": { 
     "test-shortcut": { 
      "suggested_key": { 
       "default": "Ctrl+D", 
       "mac": "Command+D", 
       "linux": "Ctrl+D" 
      }, 
      "description": "Whatever you want" 
     } 
    } 
} 

background.js

// Chrome 24+. Use chrome.experimental.commands in Chrome 23- 
chrome.commands.onCommand.addListener(function(command) { 
    if (command === 'test-shortcut') { 
     // Do whatever you want, for instance console.log in the tab: 
     chrome.tabs.query({active:true}, function(tabs) { 
      var tabId = tabs[0].id; 
      var code = 'console.log("Intercepted Ctrl+D!");'; 
      chrome.tabs.executeScript(tabId, {code: code}); 
     }); 
    } 
}); 

文档

+0

Tx,这个工程。但是您应该记住,即使在“配置命令”对话框中更改了快捷方式,也会永久覆盖Ctrl + D。也就是说,用户将无法使用/打开默认的Chrome对话框来创建书签。 – cnmuc

2

这是没有必要使用chrome.commands - 您可以使用内容脚本套住​​事件,呼吁preventDefaultstopPropagation它,处理它,但是你想。示例代码段应工作为内容脚本的一部分:

document.addEventListener('keydown', function(event) { 
    if (event.ctrlKey && String.fromCharCode(event.keyCode) === 'D') { 
    console.log("you pressed ctrl-D"); 
    event.preventDefault(); 
    event.stopPropagation(); 
    } 
}, true); 

不能覆盖这种方式唯一的东西是窗口处理命令,就像ctrl-Nctrl-<tab>

+3

这在以下所有情况下都不起作用:1.在页面的上下文之外,如多功能框。 2.受限制的页面,例如新标签页或Chrome网上应用店。 3.隐身模式或'file://'没有适当的权限。不过,这是旧版Chrome的唯一方法。 –