Activate extension via short cut key

妖精的绣舞 提交于 2019-12-14 03:48:36

问题


Is it possible to open/initiate a google chrome extension via a short cut key. For example I would like to assign a short cut of, lets say, CTRL + E to open my extension and initiate it.

Has anyone done this before?


回答1:


UPDATE (5/24/2013): You can use the new chrome.commands API, which provides built-in framework support for keyboard commands.

Original answer follows:

Step 1: Use a content script to bind a keypress listener to every page.

// in the content script, listen for Crtl+Shift+E (upper or lowercase)
document.documentElement.addEventListener("keypress", function(event) {
    if((e.keyCode == 69 || e.keyCode == 101) && e.ctrlKey && e.shiftKey) {
        // do something (step 2, below)
    }
}, true);

Step 2: For action outside of the content script, use message passing to notify the background page that the shortcut key has been pressed and it should perform some action.

Step 3: The background page does some action. It's currently not possible (and will likely never be possible) to open a Browser Action popup programatically, but you could send an interactive desktop notification, open a new tab, or do a lot of other things.

[EDIT: Code edited to include Rob W.'s suggestions; see his important notes on security in the comment below.]



来源:https://stackoverflow.com/questions/10387712/activate-extension-via-short-cut-key

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