docs: revised the keyboard shortcuts feature page (#25999)

* docs: revised the keyboard shortcuts feature page

* docs: fixed mentions, revised sections and code samples

* docs: added example of before-input-event

* docs: fixed lint errors in keyboard shortcuts feature page

* docs: minor grammar fix in keyboard shortcuts feature page
This commit is contained in:
Antonio 2020-10-28 08:58:38 +02:00 коммит произвёл GitHub
Родитель 0603ef7bfd
Коммит bb16c6f0be
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 96 добавлений и 25 удалений

Двоичные данные
docs/images/local-shortcut.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 13 KiB

Просмотреть файл

@ -1,62 +1,131 @@
# Keyboard Shortcuts # Keyboard Shortcuts
> Configure local and global keyboard shortcuts ## Overview
## Local Shortcuts This feature allows you to configure local and global keyboard shortcuts
for your Electron application.
You can use the [Menu] module to configure keyboard shortcuts that will ## Example
be triggered only when the app is focused. To do so, specify an
[`accelerator`] property when creating a [MenuItem]. ### 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](quick-start.md), update the `main.js` file with the
following lines:
```js ```js
const { Menu, MenuItem } = require('electron') const { Menu, MenuItem } = require('electron')
const menu = new Menu() const menu = new Menu()
menu.append(new MenuItem({ menu.append(new MenuItem({
label: 'Print', label: 'Electron',
accelerator: 'CmdOrCtrl+P', submenu: [{
click: () => { console.log('time to print stuff') } role: 'help',
accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
click: () => { console.log('Electron rocks!') }
}]
})) }))
Menu.setApplicationMenu(menu)
``` ```
You can configure different key combinations based on the user's operating system. > 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`.
```js After launching the Electron application, you should see the application menu
{ along with the local shortcut you just defined:
accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I'
}
```
## Global Shortcuts ![Menu with a local shortcut](../images/local-shortcut.png)
You can use the [globalShortcut] module to detect keyboard events even when If you click `Help` or press the defined accelerator and then open the terminal
the application does not have keyboard focus. 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](quick-start.md), update the `main.js` file with the
following lines:
```js ```js
const { app, globalShortcut } = require('electron') const { app, globalShortcut } = require('electron')
app.whenReady().then(() => { app.whenReady().then(() => {
globalShortcut.register('CommandOrControl+X', () => { globalShortcut.register('Alt+CommandOrControl+I', () => {
console.log('CommandOrControl+X is pressed') console.log('Electron loves global shortcuts!')
}) })
}) }).then(createWindow)
``` ```
## Shortcuts within a BrowserWindow > NOTE: In the code above, the `CommandOrControl` combination uses `Command`
on macOS and `Control` on Windows/Linux.
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. 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][dom-events] inside the
renderer process using the [addEventListener() API][addEventListener-api].
```js ```js
window.addEventListener('keyup', doSomething, true) 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. 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`](../api/web-contents.md#event-before-input-event) event The [`before-input-event`](../api/web-contents.md#event-before-input-event) event
is emitted before dispatching `keydown` and `keyup` events in the page. It can 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. be used to catch and handle custom shortcuts that are not visible in the menu.
If you don't want to do manual shortcut parsing there are libraries that do advanced key detection such as [mousetrap]. ##### Example
Starting with a working application from the
[Quick Start Guide](quick-start.md), update the `main.js` file with the
following lines:
```js
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } })
win.loadFile('index.html')
win.webContents.on('before-input-event', (event, input) => {
if (input.control && input.key.toLowerCase() === 'i') {
console.log('Pressed Control+I')
event.preventDefault()
}
})
})
```
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:
```js ```js
Mousetrap.bind('4', () => { console.log('4') }) Mousetrap.bind('4', () => { console.log('4') })
@ -90,3 +159,5 @@ Mousetrap.bind('up up down down left right left right b a enter', () => {
[`accelerator`]: ../api/accelerator.md [`accelerator`]: ../api/accelerator.md
[BrowserWindow]: ../api/browser-window.md [BrowserWindow]: ../api/browser-window.md
[mousetrap]: https://github.com/ccampbell/mousetrap [mousetrap]: https://github.com/ccampbell/mousetrap
[dom-events]: https://developer.mozilla.org/en-US/docs/Web/Events
[addEventListener-api]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener