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.
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()
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With