chrome extension : How to get key events

前端 未结 2 1867
失恋的感觉
失恋的感觉 2020-12-13 14:44

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

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


        
相关标签:
2条回答
  • 2020-12-13 15:00

    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!

    0 讨论(0)
  • 2020-12-13 15:05

    I assume you want to implement hotkeys for your extension. Your code should in fact work, except it works on the background page, which is usually not open to catch key presses.

    To catch keypresses globally, or at least on web pages, you will have to use a content script that sends messages to the background page. The content script is injected to the open web page and insert methods for catching keypresses, and then send a message to the background page with information on which keys are pressed.

    0 讨论(0)
提交回复
热议问题