Electron does not listen keydown event

落爺英雄遲暮 提交于 2019-12-11 03:26:27

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/40763427/electron-does-not-listen-keydown-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!