Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Electron window background color without need to recreate window?

I'd like to set the background color dynamically in an Electron window without recreating the window. For my purposes, simply setting the color of an element like body with CSS is not sufficient unfortunately.

It appears that only BrowserView has a setBackgroundColor function according to the documentation.

BrowserWindow does have the function, but unfortunately it doesn't work. Is there any known alternative?

like image 788
Slbox Avatar asked Aug 31 '25 17:08

Slbox


1 Answers

It works for me when applying background color on BrowserWindow directly. It seems to be undocumented but it exists (from 0.34.1 on)

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

function createWindow () {
  let mainWindow = new BrowserWindow({
    transparent: true
  })
  mainWindow.loadURL("http://browserify.org") // transparent background
  mainWindow.setBackgroundColor('#56cc5b10') // turns opaque brown
}
app.on('ready', createWindow)

Update (2021): It is also possible to set the background color directly when creating the window: mainWindow = new BrowserWindow({ backgroundColor: "#RRGGBB", ... });

(thanks, @carlosrafaelgn)


Doing the same from renderer process seems to be buggy indeed.

However I noticed that if you un-focus then focus the window it'll start working properly.

  <script>
    const { remote } = require('electron')
    const mainWindow = remote.getCurrentWindow()
    mainWindow.setBackgroundColor('#56cc5b10')
    mainWindow.blur()
    mainWindow.focus()
  </script>
like image 184
pergy Avatar answered Sep 02 '25 07:09

pergy