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?

Upvotes: 17

Views: 15449

Answers (6)

JSBhalodia
JSBhalodia

Reputation: 259

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');
});

Upvotes: 20

Solomon Gbadamosi
Solomon Gbadamosi

Reputation: 121

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'))

})

Upvotes: -1

Stud
Stud

Reputation: 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)

Upvotes: -1

fanlion
fanlion

Reputation: 49

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/

Upvotes: 0

Blesson Kuriakose
Blesson Kuriakose

Reputation: 41

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/

Upvotes: 2

MentaVenkataSai
MentaVenkataSai

Reputation: 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"

Upvotes: -1

Related Questions