Can someone explain me how can I bind a key likewise "ctrl+k" to a javascript piece of code to be ran linked to a google chrome extension? This should work on any webpage that is opened.
In your manifest, you specify:
"commands": {
"my-command-name": {
"suggested_key": {
"default": "Ctrl+K",
},
"description": "My description"
}
}
Then, in your background page you can do:
chrome.commands.onCommand.addListener(function(command) {
if(command === "my-command-name") {
// Do your stuff
}
});
EDIT
One issue seems to be that the combination Ctrl+K
won't be assigned by default by Chrome because it's normally used for another purpose. If you specify Ctrl+K
as the default shortcut, the command will not have a shortcut assigned, and the user needs to assign one from the 'Keyboard shortcuts' link at the bottom of the chrome://extensions
page.
If you use another combination, like Ctrl+Shift+K
it will probably be automatically assigned by Chrome. You can always check the shorcuts assignations in the link mentioned, and programmatically using chrome.commands.getAll
.
Also note that if you change the manifest and reload the extension, changes in the suggested shortcut key won't have any effect. You need to remove the extension and add it again for the suggested shorcut key to be considered.