禁用电子应用程序中的键盘快捷键重新加载功能

16

我希望在一个 electron 应用程序中实现绑定到 Command+R 键盘快捷键的自定义操作。

我克隆了 electron-quick-start 存储库,并将 main.js 文件更改为以下内容:

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()
  }
})

当应用程序运行npm start时,菜单可以使用。但是,当你按下 ⌘R 时,页面重新加载而不是执行在模板中定义的自定义快捷方式。

这里有什么我漏掉了吗?


2
当您打包应用程序时,开发人员的快捷方式被禁用了,您有检查过吗?我也遇到了同样的问题,在一个无框架的Windows上。 - Paulo Galdo Sandoval
这似乎仍然是一个问题。即使在禁用 devTools 的捆绑应用程序中,也无法捕获 CMD+R(或 CTRL+R 或 F5)快捷键。有人解决了这个问题吗?实际上,您可以捕获事件,但无法停止传播或防止默认操作。 - Radko
6个回答

15

这里是简单的解决方案::

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

这应该是被接受的答案。(四年后) - spot
成功了!非常感谢。对于Linux,还有另一个命令“CommandOrControl+Shift+R”(强制重新加载)。 - Anderson Laverde
这个答案很好,但是它没有考虑到用户同时按住Shift键,正如Anderson所指出的那样。确保你也包括这些! - undefined

2
最好使用类似 mousetrap 的东西。

https://github.com/ccampbell/mousetrap

我在electronjs.org上找到了这个解决方案 https://www.electronjs.org/docs/tutorial/keyboard-shortcuts 使用全局快捷键的解决方案并不理想。 使用全局快捷键会禁用该快捷键在所有应用程序中的使用,而不仅仅是您的应用程序。
例如:如果您使用全局快捷键在您的应用程序中禁用Ctrl+R,则尝试在浏览器中刷新YouTube视频时,它将阻止您这样做。
编辑: 另一个解决方案 http://www.openjs.com/scripts/events/keyboard_shortcuts/

我认为你在这个方面是错误的,“使用globalShortcut将禁用该快捷键,不仅仅是在你的应用程序中”。我在Windows 10和11上测试了Electron应用程序。 - Naveen Kumar

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

来自https://electron.guide/final-polish/renderer/


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

})

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

-1
!isDev &&
app.whenReady().then(() => {
  globalShortcut.register("CommandOrControl+R", () => {
    console.log("CommandOrControl+R is pressed: Shortcut Disabled");
  });
});

这是上述代码片段的官方文档链接。 根据开发或生产环境,您可以使用依赖{{link2:"electron-is-Dev"}}动态禁用或启用快捷方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接