Keyboard Shortcuts

    Example

    Local keyboard shortcuts are triggered only when the application is focused. To configure a local keyboard shortcut, you need to specify an property when creating a MenuItem within the module.

    Starting with a working application from the Quick Start Guide, update the main.js file with the following lines:

    After launching the Electron application, you should see the application menu along with the local shortcut you just defined:

    If you click Help or press the defined accelerator and then open the terminal that you ran your Electron application from, you will see the message that was generated after triggering the click event: “Electron rocks!”.

    To configure a global keyboard shortcut, you need to use the module to detect keyboard events even when the application does not have keyboard focus.

    Starting with a working application from the Quick Start Guide, update the file with the following lines:

    Using web APIs

    If you want to handle keyboard shortcuts within a BrowserWindow, you can listen for the keyup and keydown inside the renderer process using the addEventListener() API.

    Intercepting events in the main process

    The before-input-event event is emitted before dispatching keydown and keyup events in the page. It can be used to catch and handle custom shortcuts that are not visible in the menu.

    Starting with a working application from the , update the main.js file with the following lines:

    Using third-party libraries

    If you don’t want to do manual shortcut parsing, there are libraries that do advanced key detection, such as . Below are examples of usage of the mousetrap running in the Renderer process: