当我调用 win.loadFile(..) 时,Electron BrowserView 正在失去焦点

Electron BrowserView is losing focus when I call win.loadFile(..)

在我的 Electron 设置中,我会在应用程序加载后显示一个基于 Web 的登录屏幕。它位于充满应用程序屏幕的 BrowserView 中 space。通过这种方法,我可以为登录页面禁用 nodeIntegration(因为它需要 jQuery,当 nodeIntegration 为 true 时不可用),同时为我的主应用程序保持启用状态。

但我注意到从关闭登录视图到加载主应用程序之间存在延迟。例如可能需要 2 - 5 秒。

为了消除这种延迟,我已经开始使用 'did-finish-load' 事件预加载主应用程序。这意味着当出现登录屏幕时,我可以在 "background".

中加载主应用程序

但是我遇到了 BrowserView 失去焦点的问题。这意味着用户需要手动点击登录输入。在我添加对 win.loadFile('index.html').

的调用后开始出现这种情况

到目前为止,我已经能够通过在主应用程序加载后将焦点传递回 BrowserView 来缓解这种情况。但这并不完美,因为有一个短暂的停滞时间,在此期间键盘输入被忽略。

是否有更好的解决方法?我的代码如下。

const win = new BrowserWindow({
    width: 605, height: 550,
    minWidth: 605, minHeight: 550,
    useContentSize: true,
    maximizable: false,
    title: "My Window"
})

const view = new BrowserView({
    webPreferences: {
      // Enables support for jQuery and others by disabling nodeIntegration in this BrowserView
      nodeIntegration: false,
    }
})

win.setBrowserView(view)
view.setAutoResize({ width: true, height: true})
view.setBounds({ x: 0, y: 0, width: win.getContentBounds().width, height: win.getContentBounds().height })

view.webContents.loadURL('my login url')

view.webContents.once('did-finish-load', () => {
    // Load the main view in the background. This means it'll be available immediately when the login view closes.
    // But it also steals focus from the view so...
    win.loadFile('index.html')

    // Best fix so far but not perfect
    win.webContents.on('did-finish-load', () => view.webContents.focus())
})

view.webContents.on('login-complete-made-up-event', async (event) => {
    // Close the login page to show the main view
    view.destroy()
    // Set the focus onto the main view
    win.webContents.focus()
})

修复相当简单。今天早上在 5 分钟内偶然发现了它。

view.webContents.once('did-finish-load', () => {
    // Load the main view in the background. This means it'll be available immediately when the login view closes.
    win.loadFile('index.html')

    // Place focus on the view for keyboard input. i.e. Otherwise the user needs to click.
    // Do this after loading index.html as the loadFile(..) steals focus
    view.webContents.focus()
})