Keyboard shortcuts in Chrome extensions

一笑奈何 提交于 2019-12-12 17:24:15

问题


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?


回答1:


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. :/




回答2:


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:

  1. 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)"
      }
    }
    
  2. 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



来源:https://stackoverflow.com/questions/8305318/keyboard-shortcuts-in-chrome-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!