Why does only one BrowserView work with Electron?

2019-04-17 12:37发布

问题:

I'm trying to have two BrowserView in the same window, side by side. This code runs:

const { app, BrowserWindow, BrowserView } = require('electron');
function createWindow() {
    browserWindow = new BrowserWindow({ width: 1200, height: 600 });
    let browserView1 = new BrowserView({ webPreferences: { nodeIntegration: false }});
    let browserView2 = new BrowserView({ webPreferences: { nodeIntegration: false }});
    browserWindow.setBrowserView(browserView1);
    browserWindow.setBrowserView(browserView2);
    browserView1.setBounds({ x: 0, y: 0, width: 600, height: 600 });
    browserView2.setBounds({ x: 600, y: 0, width: 600, height: 600 });
    browserView1.webContents.loadURL('https://www.example.com');
    browserView2.webContents.loadURL('https://www.google.com');
    browserWindow.on('closed', function () { browserWindow = null; });
}
app.on('ready', createWindow);

but only the second BrowserView is displayed.

How to have both displayed?

回答1:

The BrowserView is currently an experimental feature of Electron. Most of its functionality is still in beta releases of Electron. Since this is still only in beta releases of Electron it is not safe to use in production releases.

Having said that we can still get this to work. First, install the Electron beta npm install --save electron@v5.0.0-beta.5.

Then change your Electron file:

const { app, BrowserWindow, BrowserView } = require('electron');
function createWindow() {
    browserWindow = new BrowserWindow({ width: 1200, height: 600 });
    let browserView1 = new BrowserView({ webPreferences: { nodeIntegration: false }});
    let browserView2 = new BrowserView({ webPreferences: { nodeIntegration: false }});
    browserWindow.addBrowserView(browserView1);
    browserWindow.addBrowserView(browserView2);
    browserView1.setBounds({ x: 0, y: 0, width: 600, height: 600 });
    browserView2.setBounds({ x: 600, y: 0, width: 600, height: 600 });
    browserView1.webContents.loadURL('https://www.example.com');
    browserView2.webContents.loadURL('https://www.google.com');
    browserWindow.on('closed', function () { browserWindow = null; });
}
app.on('ready', createWindow);

Instead of using setBrowserView() use addBrowserView().

Feature request on git