Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

chrome extension : How to get key events

Is there any way to get key events in a google chrome extension file - background.html - ?

document.onkeydown = function() {
  alert('test)
};

Previous code doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure if this is still active, but an update might help someone like me who is just now playing around with Chrome extensions. The new commands api allows you to receive the same functionality without using a content script.

Use your manifest.json file to register the keyboard commands. For example:

...    
"commands": {
    "save" : {
        "suggested_key": {
             "default": "Alt+Shift+S" 
        },
        "description": "Save a link"
    },
    "random": {
        "suggested_key": {
            "default": "Alt+Shift+L"
        },
        "description": "Load a random link"
    }
}
...

and then you can catch it in your background page

chrome.commands.onCommand.addListener(function (command) {
    if (command === "save") {
        alert("save");
    } else if (command === "random") {
        alert("random");
    }
});

Hopefully that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...