Keyboard Shortcuts

Overview

This feature allows you to configure local and global keyboard shortcuts for your Electron application.

Example

Local Shortcuts

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

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

  1. // fiddle='docs/fiddles/features/keyboard-shortcuts/local'
  2. const { Menu, MenuItem } = require('electron')
  3. const menu = new Menu()
  4. menu.append(new MenuItem({
  5. label: 'Electron',
  6. submenu: [{
  7. role: 'help',
  8. accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
  9. click: () => { console.log('Electron rocks!') }
  10. }]
  11. }))
  12. Menu.setApplicationMenu(menu)

NOTE: In the code above, you can see that the accelerator differs based on the user’s operating system. For MacOS, it is Alt+Cmd+I, whereas for Linux and Windows, it is Alt+Shift+I.

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

Menu with a local shortcut

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!”.

Global Shortcuts

To configure a global keyboard shortcut, you need to use the globalShortcut 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 main.js file with the following lines:

  1. // fiddle='docs/fiddles/features/keyboard-shortcuts/global'
  2. const { app, globalShortcut } = require('electron')
  3. app.whenReady().then(() => {
  4. globalShortcut.register('Alt+CommandOrControl+I', () => {
  5. console.log('Electron loves global shortcuts!')
  6. })
  7. }).then(createWindow)

NOTE: In the code above, the CommandOrControl combination uses Command on macOS and Control on Windows/Linux.

After launching the Electron application, if you press the defined key combination then open the terminal that you ran your Electron application from, you will see that Electron loves global shortcuts!

Shortcuts within a BrowserWindow

Using web APIs

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

  1. // fiddle='docs/fiddles/features/keyboard-shortcuts/web-apis|focus=renderer.js'
  2. const handleKeyPress = (event) => {
  3. // You can put code here to handle the keypress.
  4. document.getElementById("last-keypress").innerText = event.key;
  5. console.log(`You pressed ${event.key}`);
  6. }
  7. window.addEventListener('keyup', handleKeyPress, true);

Note: the third parameter true indicates that the listener will always receive key presses before other listeners so they can’t have stopPropagation() called on them.

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 Quick Start Guide, update the main.js file with the following lines:

  1. // fiddle='docs/fiddles/features/keyboard-shortcuts/interception-from-main'
  2. const { app, BrowserWindow } = require('electron')
  3. app.whenReady().then(() => {
  4. const win = new BrowserWindow({ width: 800, height: 600 })
  5. win.loadFile('index.html')
  6. win.webContents.on('before-input-event', (event, input) => {
  7. if (input.control && input.key.toLowerCase() === 'i') {
  8. console.log('Pressed Control+I')
  9. event.preventDefault()
  10. }
  11. })
  12. })

After launching the Electron application, if you open the terminal that you ran your Electron application from and press Ctrl+I key combination, you will see that this key combination was successfully intercepted.

Using third-party libraries

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

  1. Mousetrap.bind('4', () => { console.log('4') })
  2. Mousetrap.bind('?', () => { console.log('show shortcuts!') })
  3. Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')
  4. // combinations
  5. Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })
  6. // map multiple combinations to the same callback
  7. Mousetrap.bind(['command+k', 'ctrl+k'], () => {
  8. console.log('command k or control k')
  9. // return false to prevent default behavior and stop event from bubbling
  10. return false
  11. })
  12. // gmail style sequences
  13. Mousetrap.bind('g i', () => { console.log('go to inbox') })
  14. Mousetrap.bind('* a', () => { console.log('select all') })
  15. // konami code!
  16. Mousetrap.bind('up up down down left right left right b a enter', () => {
  17. console.log('konami code')
  18. })