Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Keyboard shortcuts

A keyboard shortcut is a key combination that runs a command without the mouse. Electron has three kinds: menu accelerators work while the app window is focused; global shortcuts work always, even with the app in the background; and handlers on the page catch keys inside the window.

This is the main way. The combination goes into the accelerator property of a menu item, as in the application menu lesson:

// main.js
{
  label: 'Export',
  accelerator: 'CmdOrCtrl+E',
  click: (menuItem, win) => win?.webContents.send('menu:export'),
},

Ctrl+E on Windows or Cmd+E on macOS runs the item, and the combination is shown in the menu next to its name.

Writing combinations

NotationKeys
CmdOrCtrlCmd on macOS, Ctrl on other systems
Alt, ShiftAlt (Option on macOS) and Shift
F1 … F24Function keys
Plus, Space, TabPlus, space, Tab
CmdOrCtrl+Shift+NSeveral keys joined with +

A global shortcut

The globalShortcut module registers a combination system-wide. Let Ctrl+Shift+N from any app open Notes with an empty field:

// main.js
const { app, globalShortcut } = require('electron');
 
app.whenReady().then(() => {
  createWindow();
 
  const ok = globalShortcut.register('CmdOrCtrl+Shift+N', () => {
    win.show();
    win.webContents.send('menu:new-note');
  });
  if (!ok) {
    console.log('The shortcut is taken by another app');
  }
});
 
app.on('will-quit', () => {
  globalShortcut.unregisterAll();
});

register returns false if the combination is already taken. On quit all shortcuts are released so they do not get in other apps' way.

Keys before the page

The before-input-event event of webContents intercepts a key before the page gets it. For example, block Ctrl+R so the user does not reload the window by accident:

// main.js
win.webContents.on('before-input-event', (event, input) => {
  if (input.control && input.key.toLowerCase() === 'r') {
    event.preventDefault();
  }
});

input has key, control, shift, alt and meta. preventDefault cancels the key press.

Keys on the page

Shortcuts that only concern the window's content are handled with ordinary browser code:

// renderer.js
text.addEventListener('keydown', (event) => {
  if (event.key === 'Enter' && event.ctrlKey) {
    form.requestSubmit();
  }
});

Ctrl+Enter in the note field submits the form, like the Add button.

Common mistake

A global shortcut is taken away from every other app. If you register a familiar combination such as CmdOrCtrl+C or CmdOrCtrl+S with globalShortcut, it stops working in the browser and the editor while Notes is running. Use menu accelerators for commands inside the app, and keep global ones for one or two rare combinations.

Thanks for reading!

Donate to the site — we work hard for you.