Electron:如何与浏览器通信 window?

Electron: How do I communicate with browser window?

在 Electron 中,我有以下脚本是我的 main.js,它是恢复 window 并聚焦它的快捷方式,但是我想聚焦 window 内的输入.我该如何实现?

main.js

app.on('ready', function(){
  createWindow();
  var ret = globalShortcut.register('Command+Control+Alt+G', function() {
    mainWindow.restore();
    mainWindow.focus();
    $('.js-search').focus();
  });
})

您可以在页面获得焦点时使用 webContents 从主进程向呈现器进程发送消息。

页面(呈现器进程)可以侦听该消息,然后聚焦元素本身。

主要流程

globalShortcut.register('Command+Control+Alt+G', function() {

    win.restore();
    win.focus();
    win.webContents.send('focus-element', '.js-search');
});

渲染进程(页面)

<script>
    const {ipcRenderer} = require('electron');

    ipcRenderer.on('focus-element', (event, selector) => {
        document.querySelector(selector).focus();
    });
</script>