简体   繁体   中英

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.

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

You can use the library mousetrap to add global short cut, because it can be installed through node and could bypass the problem of electron mentioned in the accepted answer.

A code example in the render process would be:

var Mousetrap = require('mousetrap');
Mousetrap.bind('4', function() { console.log('4'); });

Without additional libraries you can use "globalShortcut" of electron

const { app, BrowserWindow, globalShortcut } = require("electron");
globalShortcut.register("CmdOrCtrl+F12", () => {
  mainWindow.isFocused() && mainWindow.webContents.toggleDevTools();
});

I think F12 is preserved so I use ctrl+f12 which is not far off

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM