The only way I decided to do this without the onkeydown listener is with the global shortcut and ipc events in the Electron api element.
First a reservation ...
Disabling any key using the global shortcut really disables its GLOBALY on your computer! PLEASE CAUTION WHEN USING GLOBAL SHORT! If you forget to unregister your shortcut or do not process it properly, it will be difficult for you to correct your mistake without backspace!
That says this is what worked for me ...
const { app, ipcMain, globalShortcut, BrowserWindow, } = require('electron'); app.on('ready', () => { // Create the browser window let mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Register a 'Backspace' shortcut listener when focused on window mainWindow.on('focus', () => { if (mainWindow.isFocused()) { globalShortcut.register('Backspace', () => { // Provide feedback or logging here // If you leave this section blank, you will get no // response when you try the shortcut (ie Backspace). console.log('Backspace was pressed!'); //comment-out or delete when ready. }); }); }); // ** THE IMPORTANT PART ** // Unregister a 'Backspace' shortcut listener when leaving window. mainWindow.on('blur', () => { globalShortcut.unregister('Backspace'); console.log('Backspace is unregistered!'); //comment-out or delete when ready. }); });
Alternatively, you can add a shortcut inside the ipc "Toggle" event handler, like this ...
// In the main process ipcMain.on('disableKey-toggle', (event, keyToDisable) => { if (!globalShortcut.isRegistered(keyToDisable){ globalShortcut.register(keyToDisable, () => { console.log(keyToDisable+' is registered!'); //comment-out or delete when ready. }); } else { globalShortcut.unregister(keyToDisable); console.log(keyToDisable+' is unregistered!'); //comment-out or delete when ready. } }); // In the render process send the accelerator of the keyToDisable. // Here we use the 'Backspace' accelerator. const { ipcRenderer } = require('electron'); ipcRenderer.send('disableKey-toggle', 'Backspace');
source share