回答

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的唯一方法。 –