I want to implement a custom action bound to the Command+R
keyboard shortcut in an electron application.
I cloned the electron-quick-start
repo, and changed the main.js
file to this:
const { app, Menu, MenuItem, BrowserWindow } = require('electron')
let mainWindow
let template = [
{ label: app.getName(), submenu: [
{ label: 'custom action 1', accelerator: 'Command+R', click() { console.log('go!') } },
{ label: 'custom action 2', accelerator: 'Shift+Command+R', click() { console.log('go!') } },
{ type: 'separator' },
{ role: 'quit' }
] }
]
const menu = Menu.buildFromTemplate(template)
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () { mainWindow = null })
// Set application menu
Menu.setApplicationMenu(menu)
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
The menu works when the app is run npm start
. But when you press ⌘R the page reloads instead of performing the custom shortcut defined in the template.
Anything I'm missing here?
Here is simple solution ::
app.on('browser-window-focus', function () {
globalShortcut.register("CommandOrControl+R", () => {
console.log("CommandOrControl+R is pressed: Shortcut Disabled");
});
globalShortcut.register("F5", () => {
console.log("F5 is pressed: Shortcut Disabled");
});
});
app.on('browser-window-blur', function () {
globalShortcut.unregister('CommandOrControl+R');
globalShortcut.unregister('F5');
});
It would be better to use something like mousetrap
https://github.com/ccampbell/mousetrap
I found this solution on electronjs.org https://www.electronjs.org/docs/tutorial/keyboard-shortcuts
Solutions that involve globalShortcut are not optimal. Using globalShortcut will disable that shortcut for EVERYTHING, not only in your application.
Ex: If you use globalShortcut to disable Ctrl+R in your app, then try to refresh a youtube video in your browser, it'll prevent you from doing so.
EDIT: Another solution http://www.openjs.com/scripts/events/keyboard_shortcuts/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With