Inject CSS to loadURL


#1

Hi there

Is it possible to inject a custom CSS in to the webview I’m loading? There is a function called: webContents.insertCSS(css) -> string but I’m unable to track any example of the usage. Does anyone know how to use it? Examples?

Thanks


#2

webview.insertCSS(“body { background-color: red !important; }”);


Frameless window draggable
#3
let mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(`www.test.com`)
mainWindow.webContents.on('did-finish-load', function() {
 	mainWindow.webContents.insertCSS('html,body{ background-color: #FF0000 !important;}')
});

#4

Your method works!

I’m trying to inject CSS from the file thought. eg.

mainWindow.webContents.insertCSS('@import url("file://${__dirname}/styles.css")')

But this way seams to be more tricky.

Any ideas? Thanks


#5

use ‘file-system’ node module to read your css file. Remeber to use ‘utf-8’ encoding otherwise it will output as a bite stream.
const fs = require(‘file-system’);
let mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(www.test.com)
mainWindow.webContents.on(‘did-finish-load’, function() {
// this is with async way
fs.readFile(__dirname+ ‘/test.css’, “utf-8”, function(error, data) {
if(!error){
mainWindow.webContents.insertCSS(data’)
}
})
});

your test.css will contain the styles with ‘!important’ declaration


#6

Hi nfours

Thanks for your help, the solution almost worked :wink: for me:

const fs = require('fs')

let mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(www.test.com)
mainWindow.webContents.on('did-finish-load', function() {

fs.readFile(__dirname+ '/test.css', "utf-8", function(error, data) {
if(!error){
var formatedData = data.replace(/\s{2,10}/g, ' ').trim()
mainWindow.webContents.insertCSS(formatedData)
}
})
})

I had to call the file system with ‘fs’ rather than ‘file-system’ also to handle css file formating spaces and carriage returns I had to add a regex for that. Now everything is working perfectly.