Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron does not listen keydown event

I am a backend developer who got a little project to fix it. So my boss gives me an electron project which runs on touch devices.

I know that I can listen any key events in Javascript if I use the document object, but in electron it does not work, it says the docuemnt cannot be found.

So implemented this when I or other support guy press the F12 button then the dev tools be rendered out in the electron app.

mainWindow = new BrowserWindow({
    'web-preferences': {'web-security': false}
  });

  mainWindow.onkeydown = function (e) {
    console.log("Key down");
    if (e.which === 123) {
      console.log("Key is F12");
      mainWindow.webContents.openDevTools();
    }
  };

But this code is not working to me. I have no idea how I can listen the F12 button is pressed.

Unfortunately I cannot render out button to the UI which can show the devtools. Because of the customers mustn't press it.

Sometimes I need to see the realtime console tab in devtools on the device.

like image 583
Dabagab Avatar asked Oct 26 '25 16:10

Dabagab


1 Answers

There is a known issue in Electron ( which has lately been marked as wontfix ) that prevents the usual approach to catch key events using the traditional JS approach.

There also is a small library called electron-localshortcut that circumvents this issue by hijacking the Electron global shortcuts API when the window is active.

Use like this in your main.js:

const electronLocalshortcut = require('electron-localshortcut');
electronLocalshortcut.register(mainWindow, 'F12', () => {
    // Open DevTools
});
like image 186
Jens Habegger Avatar answered Oct 29 '25 05:10

Jens Habegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!