Search code examples
javascriptelectronkeyboard-shortcuts

How to make an event listener work when you are on a different application


I was using electronjs to create an app with event listener and one of the function was that when the “a” key is pressed on your keyboard, something happens. However when I am on a different app, this listener doesn’t work.

The code for the eventlistener is:

document.addEventListener('keydown', (event) => {
  //function
}

Solution

  • You need to register a globalShortcut, just remember to unregister it when the app is going to quit.

    Here's documentation for the keys & modifiers you can use: https://www.electronjs.org/docs/api/accelerator

    const { app, globalShortcut } = require('electron')
    
    app.whenReady().then(() => {
      // Register a 'A' shortcut listener.
      const ret = globalShortcut.register('A', () => {
        console.log('A is pressed')
      })
    
      if (!ret) {
        console.log('registration failed')
      }
    
      // Check whether a shortcut is registered.
      console.log(globalShortcut.isRegistered('A'))
    })
    
    app.on('will-quit', () => {
      // Unregister a shortcut.
      globalShortcut.unregister('A')
    
      // Unregister all shortcuts.
      globalShortcut.unregisterAll()
    })