Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide (not destroy) a BrowserView in Electron

Tags:

electron

I'm working in Electron 5.0.3 and I want to hide a BrowserView such that the BrowserView doesn't need to be re created. I don't have any preference on how this should be achieved. Any solution (JS, CSS, etc.) would suffice.

I've looked through the BrowserView documentation and there is nothing in here that i see that could help, and moving the BrowserView to somewhere off screen isn't exactly ideal.

like image 715
Daniel Turcich Avatar asked Jun 12 '19 14:06

Daniel Turcich


2 Answers

First Solution (optimal):

browserWindow.addBrowserView(browserView)
browserWindow.removeBrowserView(browserView)

addBrowserView() & removeBrowserView(). Removing the browser view is the same as hiding, it will not make the browserView re-render.

Secondary solution (not optimal):

// not optimal if you call more than once because it will constantly add more CSS
browserView.webContents.insertCSS('html{display: block}')
browserView.webContents.insertCSS('html{display: none}')

insertCSS()

like image 152
Daniel Turcich Avatar answered Nov 11 '22 10:11

Daniel Turcich


I know this is old but I ran into a problem with this solution and have an alternative.

There are scenarios where removing the BrowserView from the BrowserWindow can have some unintended consequences. I have found that if you are using a BrowserView to host external content that while removing and setting seems to preserve the content, you may lose some ability to interact with it via code (e.g. via view.webContents.executeJavaScript()) or in some circumstances UI controls that call an async event sometimes stop working altogether.

If all you want to do is hide the BrowserView, setting the bounds to 0 works really well:

  view.setBounds({ x: 0, y: 0, width: 0, height: 0 })

Then restore it using the host BrowserWindow dimensions:

  let wb = win.getBounds()
  view.setBounds({ x: 0, y: 0, width: wb.width, height: wb.height })

Side note: there is a difference between setBrowserView() and addBrowserView(). The former will remove all other BrowserViews from the BrowserWindow (meaning there is no need to explicitly remove a view if you are also setting it and that if you are using add you need to manage your views.)

like image 4
jtvberg Avatar answered Nov 11 '22 08:11

jtvberg