15

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
    when you package your application the shorcuts of dev are disabled, did you checked that? i've have the same problem, in a windows frameless – Paulo Galdo Sandoval Aug 28 '16 at 16:43
  • This seems to be still an issue. There's no way to catch the CMD+R (or CTRL+R or F5) shortcut even in bundled app with devTools disabled. Anybody figured this out? Actually, you can catch the event, but there's no way to stop propagation or preventing default action. – Radko Mar 30 '20 at 20:57

6 Answers6

13

Here is simple solution ::

const { globalShortcut } = require('electron');
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');
});
Anthony L
  • 2,159
  • 13
  • 25
JSBhalodia
  • 181
  • 2
  • 8
2

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/

  • I think you are wrong in the aspect that " Using globalShortcut will disable that shortcut for EVERYTHING, not only in your application". I tested for electron app on windows 10 and 11. – Naveen Kumar Jun 14 '23 at 13:55
1

Prevent BrowserWindow refreshes

A user can press Cmd+R (on macOS) or Ctrl+R/Ctrl+Shift+R/F5 (on Windows) to refresh the webpage shown by the BrowserWindow. True native applications don’t exhibit this behaviour.

The recommended solution is to replace the default menu to disable this behaviour. On Windows, you can call win.removeMenu(). On macOS, you can call Menu.setApplicationMenu(Menu.buildFromTemplate([])). You should only do it for production since you will lose access to DevTools.

For Kiosk Mode, another solution is to Disable the keyboard shortcuts when the BrowserWindow takes focus and then unregister the shortcuts when the BrowserWindow loses focus or is closed/hidden.

const electronLocalshortcut = require('electron-localshortcut')

win.on('focus', (event) => {
    electronLocalshortcut.register(win, ['CommandOrControl+R','CommandOrControl+Shift+R', 'F5'], () => {})
})

win.on('blur', (event) => {
    electronLocalshortcut.unregisterAll(win)
})

From https://electron.guide/final-polish/renderer/

Edric
  • 24,639
  • 13
  • 81
  • 91
fanlion
  • 51
  • 1
-1
!isDev &&
app.whenReady().then(() => {
  globalShortcut.register("CommandOrControl+R", () => {
    console.log("CommandOrControl+R is pressed: Shortcut Disabled");
  });
});

this is the link to official docs for above code snippet. Based on development or Production you can disable or enable shortcuts dynamically using dependency "electron-is-Dev"

-1
// main.js
const { Menu, MenuItem } = require('electron')

const menu = new Menu()
menu.append(new MenuItem({
  label: '',
  submenu: [{
    accelerator: 'CommandOrControl+R',
    click: () => { }
  }]
}))

Menu.setApplicationMenu(menu)
Stud
  • 1
-1
app.whenReady().then(() => {

  const mainWindow = new BrowserWindow({
    // width: 800,
    // height: 800,
    resizable: false,
    frame: false,
    webPreferences: {
      preload: path.join(__dirname,'preloader.js'),
    },
   
  }
})

mainWindow.webContents.on('before-input-event', (event, input) => {
  if (input.control && input.key.toLowerCase() === 'r') {
    event.preventDefault()
  }
})


mainWindow.loadURL(path.join(__dirname, 'index.html'))

})