Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable reload via keyboard shortcut electron app

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?

like image 378
Aᴄʜᴇʀᴏɴғᴀɪʟ Avatar asked Aug 28 '16 10:08

Aᴄʜᴇʀᴏɴғᴀɪʟ


2 Answers

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');
});
like image 53
JSBhalodia Avatar answered Sep 21 '22 12:09

JSBhalodia


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/

like image 23
Blesson Kuriakose Avatar answered Sep 19 '22 12:09

Blesson Kuriakose