Reputation: 2875
I'm creating an extension that will allow users to use chrome-like tab switching on Vivaldi browser.
In my background.js I have tried
addEventListener("keydown", function(e) {
console.log(e.code); // never gets here
})
I originally had the event being handled by a content.js script, however this required any new tabs to be completely loaded before I could send messages to the background.js script
function Listener()
{
this.stage = 0;
this.listen();
}
Listener.prototype.listen = function()
{
addEventListener("keydown", this.handleKeyDown);
addEventListener("keyup", this.handleKeyUp);
}
Listener.prototype.handleKeyDown = function(event)
{
for(var i = 0; i < 9; i++) {
if(event.ctrlKey) {
if(event.code == "Digit" + (i + 1)) {
chrome.runtime.sendMessage({
greeting: i
}, function(response) {
console.log(response);
})
}
}
}
}
new Listener();
I want to move this functionality to my background.js so that it runs independently of browser actions.
Upvotes: 2
Views: 7423
Reputation: 77523
DOM keyboard event listeners capture only keystrokes that happen when the focus is within the page.
A background page cannot be shown, and as such, cannot be focused. It will never receive any input events.
You may want to look into chrome.commands
API, but it is fairly restrictive. For a good reason: you really, really don't want extensions to be able to just harvest all keystrokes.
You could partially bypass the restrictions by using a (valid) command to invoke your extension, which would open its popup, which in turn can capture further events with DOM listeners.
Upvotes: 5