electron/docs/tutorial/keyboard-shortcuts.md
2017-02-28 08:44:12 -08:00

2.5 KiB

Keyboard Shortcuts

Configure local and global keyboard shortcuts

Local Shortcuts

You can use the Menu module to configure keyboard shortcuts that will be triggered only when the app is focused. To do so, specify an accelerator property when creating a MenuItem.

const {Menu, MenuItem} = require('electron')
const menu = new Menu()

menu.append(new MenuItem({
  label: 'Print',
  accelerator: 'CmdOrCtrl+P',
  click: () => { console.log('time to print stuff') }
}))

It's easy to configure different key combinations based on the user's operating system.

{
  accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I'
}

Global Shortcuts

You can use the globalShortcut module to detect keyboard events even when the application does not have keyboard focus.

const {app, globalShortcut} = require('electron')

app.on('ready', () => {
  globalShortcut.register('CommandOrControl+X', () => {
    console.log('CommandOrControl+X is pressed')
  })
})

Shortcuts within a BrowserWindow

If you want to handle keyboard shortcuts for a BrowserWindow, you can use the keyup and keydown event listeners on the window object inside the renderer process.

window.addEventListener('keyup', doSomething, true)

Note the third parameter true which means the listener will always receive key presses before other listeners so they can't have stopPropagation() called on them.

If you don't want to do manual shortcut parsing there are libraries that do advanced key detection such as mousetrap.

Mousetrap.bind('4', () => { console.log('4') })
Mousetrap.bind('?', () => { console.log('show shortcuts!') })
Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')

// combinations
Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })

// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], () => {
  console.log('command k or control k')

  // return false to prevent default behavior and stop event from bubbling
  return false
})

// gmail style sequences
Mousetrap.bind('g i', () => { console.log('go to inbox') })
Mousetrap.bind('* a', () => { console.log('select all') })

// konami code!
Mousetrap.bind('up up down down left right left right b a enter', () => {
  console.log('konami code')
})