电子不监听按键事件 [英] 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.
我知道如果使用<$,我可以收听Javascript中的任何关键事件。 c $ c> document 对象,但在电子中不起作用,它表示找不到 docuemnt
。
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
.
当我或其他支持人员按F12按钮然后将开发工具呈现在电子应用程序中时,请执行此操作。
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();
}
};
但是此代码对我不起作用。我不知道如何收听F12按钮。
But this code is not working to me. I have no idea how I can listen the F12 button is pressed.
不幸的是,我无法向可以显示devtools的UI渲染按钮。
Unfortunately I cannot render out button to the UI which can show the devtools. Because of the customers mustn't press it.
有时候,我需要在设备上的devtools中看到实时控制台选项卡。
Sometimes I need to see the realtime console tab in devtools on the device.
推荐答案
Electron中存在一个已知问题(最近被标记为 wontfix
)阻止了使用传统JS方法捕获键事件的常用方法。
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.
还有一个名为 electron-localshortcut 的小型库通过在窗口处于活动状态时劫持Electron全局快捷方式API来解决此问题。
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.
在main.js中这样使用:
Use like this in your main.js:
const electronLocalshortcut = require('electron-localshortcut');
electronLocalshortcut.register(mainWindow, 'F12', () => {
// Open DevTools
});
这篇关于电子不监听按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!