Listening on keypresses when browser is out of focus

Viewed 98

Is there a way to listen for keyboard events on a webpage even if the tab and or window is not active (running but not the foreground application). I would assume no due to security concerns but maybe there is some way to archive it with explicit permissions? A service worker?

Basically what I'm trying to do is as following:

window.addEventListener('keydown', event => {
    console.log(event.code);
});

As long as the tab is active it works as expected but if the user switches to another application it stops receiving input (also expected), but I am hoping for a way to add a "global" listener.

I know that I'm basically asking for a keylogger but the use-case is a webbased audio player which supports media keys (play/pause, next track, etc) present on some keyboards.

1 Answers

Fairly certain that even here in 2017, the answer to this is "no" for the reason you gave: It's just a huge security concern. Reviewing the list of permissions for pages in both Chrome1 and Firefox2 doesn't suggest any explicit permission for this. (Server workers would be irrelevant to it.)


1 If you click the lock/info/dangerous icon next to the page's URL, you can see all available permissions in Chrome (source).

2 It's similar in Firefox: Click the icon, click the > arrow, then "More Information".

Related