I would like to know if there is a way to make an application with Atom Electron that runs and gets my keyboard events when the user is/isn't focused on my app.
For example if he is on Chrome and writes something, my app will store all the keys that he pressed. I searched a little but didn't find something that solves my problem.
I would like to know if there is a way to make an application with Atom Electron that runs and gets my keyboard events when the user is/isn't focused on my app.
For example if he is on Chrome and writes something, my app will store all the keys that he pressed. I searched a little but didn't find something that solves my problem.
Share Improve this question edited Sep 8, 2016 at 16:22 Paul Roub 36.4k27 gold badges85 silver badges94 bronze badges asked Sep 8, 2016 at 13:15 Nistor CristianNistor Cristian 1,2661 gold badge10 silver badges26 bronze badges 2- 4 Sounds like you're trying to do something bad – Patrick Michaelsen Commented Oct 19, 2018 at 4:41
- There are valid uses for this for listening to all keys, like a clipboard utility. That doesn't sound like the case here though. – Slbox Commented Oct 24, 2020 at 0:47
3 Answers
Reset to default 12The closest thing there is to what you're looking for is global shortcuts: https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md. While you don't have anything in core Electron to support capturing all keyboard events out of the box, luckily node.js is pretty extensible with native node addons.
For global shortcuts you can use Electron Keyboard-Shortcuts module
const {app, globalShortcut} = require('electron')
app.on('ready', () => {
globalShortcut.register('CommandOrControl+X', () => {
console.log('CommandOrControl+X is pressed')
})
})
But this module support only shortcuts.
If you need any key listening/hooking you should use another module like iohook
const ioHook = require('iohook');
ioHook.on("keyup", event => {
console.log(event); // {keychar: 'f', keycode: 19, rawcode: 15, type: 'keup'}
});
ioHook.start();
According to the doc using globalShortcut will apply keyboard short to everywhere even though our window is no in the focused state. But if you only want to listen key events within your application window. Then you can use the normal keyup
, keydown
events. But it is a little longer way because to communicate those events from render to main process we have to setup preload script.
You will get idea about listening events from render to main process inside this post.