Disable reload via keyboard shortcut electron app


#1

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?


#2

Yeah, they are building the menu in another file and that’s why you are still seeing the reload occur.

check out main-process/menus/application-menu.js


#3

This is for the https://github.com/electron/electron-quick-start project, not the https://github.com/electron/electron-api-demos FYI.
There’s no separate file for the application menu in electron-quick-start.


#4

Sorry… change your accelerator to CmdOrCtrl+R instead of Command+R.


#5

Nice, that seemed to work. :thumbsup:

That functionality seems strange though - when building my own menu I would think the app doesn’t have any ‘default’ shortcuts so-to-speak. Especially if I define an accelerator to haveCmd+R I would think it should override. Does CmdOrCtrl+R have higher precedence or something?