Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 719
canardman Avatar asked Sep 05 '25 16:09

canardman


1 Answers

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!

like image 63
topstriker515 Avatar answered Sep 07 '25 16:09

topstriker515