如何在专注于开发工具的同时在 Electron 应用程序中切换开发工具?

2023-12-24

我想让我的 Electron 应用程序切换开发人员工具以响应 F12。

在渲染器页面中,我添加了:

const currentWebContents = require("electron").remote.getCurrentWebContents();
window.addEventListener("keydown", (e: KeyboardEvent) => {
    if (e.keyCode === 123) { // F12
        currentWebContents.toggleDevTools();
    }
});

This works when I'm focused on the main page. However, immediately after the dev tools opens up, focus goes to the dev tools, so F12 is no longer detected.

我尝试通过在调用后立即向 devtools webcontents 添加监听器来解决此问题toggleDevTools()像这样:

if (currentWebContents.devToolsWebContents) {
    currentWebContents.devToolsWebContents.on("before-input-event", (event: Electron.Event, input: Electron.Input) => {
        if (input.type === "keyDown" && input.key === "F12") {
            currentWebContents.toggleDevTools();
        }
    });
}

然而,currentWebContents.devToolsWebContents is null打开后。我的第一个问题是如何确保它不是null- 有没有办法等到它完全打开?

我通过将if (currentWebContents.devToolsWebContents)代码写入一个setTimeout(..., 1000);

然而,在这样做之后,我的before-input-event当专注于开发工具时按下按键时,处理程序不会被触发。

有人知道这是为什么吗?


没有简单的方法可以做到这一点。

As per 这个问题 https://github.com/electron/electron/issues/1962,您无法检测来自开发工具的输入。

一位 Electron 开发者发表了评论here https://github.com/electron/electron/issues/28770#issuecomment-827858086:

我认为这是因为toggleDevTools 菜单角色没有正确检查devtools 窗口的“父”窗口。可能可以使用toggleDevTools菜单角色检查当前聚焦的窗口是否是devtools窗口,如果是,则在打开devtools的webcontents上调用toggleDevTools,而不是在devtools窗口本身。

无论如何,这都需要Electron开发来解决。

Update:有人here https://github.com/electron/electron/issues/28770#issuecomment-841734944建议这个解决方法 - 我自己还没有尝试过:

mainWindow.webContents.on("before-input-event", (e, input) => {
    if (input.type === "keyDown" && input.key === "F12") {
      mainWindow.webContents.toggleDevTools();

      mainWindow.webContents.on('devtools-opened', () => {
        // Can't use mainWindow.webContents.devToolsWebContents.on("before-input-event") - it just doesn't intercept any events.
        mainWindow.webContents.devToolsWebContents.executeJavaScript(`
            new Promise((resolve)=> {
              addEventListener("keydown", (event) => {
                if (event.key === "F12") {
                  resolve();
                }
              }, { once: true });
            })
          `)
          .then(() => {
            mainWindow.webContents.toggleDevTools();
          });
      });
    }
  });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在专注于开发工具的同时在 Electron 应用程序中切换开发工具? 的相关文章

随机推荐