Reputation: 2759
I'm trying to hook up a keyboard shortcut for my chrome extension. I'm using a jQuery plugin for this: http://oscargodson.com/labs/jkey/.
Here's the code I'm using to test it out:
$(document).ready(function() {
function say_hello() {
alert("hello!");
}
$(document).jkey('/', say_hello);
});
I have this in my background page right now, but it doesn't work. Is this type of code something that should go in the background page, or something that's more appropriate for a content script? Or should I place it somewhere else entirely?
Upvotes: 2
Views: 776
Reputation: 377
I know this question is ancient, but just in case you haven't discovered, here's the latest solution to your problem:
Chrome extensions now have an event that will trigger whenever specific key-combinations are pressed in any chrome window (except maybe a separate incognito session, which I haven't tried), with chrome.commands
API
Here's how to set it up:
Add a "commands" key to your manifest.json root, populated with one or more commands ("Restart App" in this case). Each command should specify the desired key combination for PC and Mac. (Some combos, like ctrl-f5, are restricted, fyi. Im also not sure if description is optional or required.)
"commands": {
"Restart App": {
"suggested_key": {
"default": "Ctrl+Shift+5",
"mac": "Command+Shift+5"
},
"description": "Restart my app (Debugging)"
}
}
In background.js, bind a handler to the "onCommand" event, and filter on "command", which will match the key declared in your manifest when your combo has been pressed:
chrome.commands.onCommand.addListener(function (command)
{
if (command == "Restart App")
{
chrome.runtime.reload();
};
});
And that's it!
I've had people question the value of hotkeys, but I'm a strong advocate for them. The amount of time saved by switching a mouse/keyboard pattern to keyboard-only is probably <1sec per use, but over several heavy debug sessions it starts to add up. Adding the shortcut in the example above to apps I develop has probably saved hours of my time by now :)
Enjoy!
-Matt
Upvotes: 2
Reputation:
Background pages can't (ordinarily) be focused or clicked on, so they never receive events. You'd have to inject this as a content script.
Note that this won't work on some pages, including the New Tab page. Unfortunately, there's no way around this. :/
Upvotes: 1