Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two browsers in the same Electron window

I'd like to have one single Electron window, split in two parts:

  • the left part is a BrowserWindow loading https://gmail.com
  • the right part is another BrowserWindow loading Gmail too, but I'd like these two browsers to be "independent", i.e. the cookies/LocalStorage/etc. should be independent (like if we have a normal Chrome window vs. a incognito window) ; thus allowing to have one Gmail account on left / another account connected on the right part

  • some other UI buttons on top of the single Electron window.

This code works, but it creates 2 windows instead of one:

const { app, BrowserWindow } = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow({show: false})
  win.once('show', () => { win.webContents.executeJavaScript('validateFlights()') })
  win.loadURL('https://www.gmail.com')
  win.show()

  let win2 = new BrowserWindow({show: false})
  win2.once('show', () => { win.webContents.executeJavaScript('validateFlights()') })
  win2.loadURL('https://www.gmail.com')
  win2.show()
})

How to have them in one window?

like image 450
Basj Avatar asked Mar 06 '19 13:03

Basj


People also ask

How do you close a browser window in an electron?

getElementById("close-btn"). addEventListener("click", function (e) { var window = remote. getCurrentWindow(); window. close(); });


1 Answers

A little late, but to add two browsers within one window you have to use BrowserWindow.addBrowserView instead of BrowserWindow.setBrowserView. You'll get the following:

const { BrowserView, BrowserWindow, app } = require('electron')
function twoViews () {
  const win = new BrowserWindow({ width: 800, height: 600 })

  const view = new BrowserView()
  win.addBrowserView(view)
  view.setBounds({ x: 0, y: 0, width: 400, height: 300 })
  view.webContents.loadURL('https://electronjs.org')

  const secondView = new BrowserView()
  win.addBrowserView(secondView)
  secondView.setBounds({ x: 400, y: 0, width: 400, height: 300 })
  secondView.webContents.loadURL('https://electronjs.org')
  app.on('window-all-closed', () => {
    win.removeBrowserView(secondView)
    win.removeBrowserView(view)
    app.quit()
  })
}

app.whenReady().then(twoViews)

Once you create two BrowserView objects, you just add them to the window. You'll also want to remove the views when tearing down the application. If you don't you might get a segmentation fault.

like image 167
David Kamer Avatar answered Oct 12 '22 21:10

David Kamer