Inject CSS into <webview> Chrome / Electron / HTML / CSS / JS
Can anyone tell me why below works? I apologize for any mistakes I'm new to all of this
Html
<webview id="wv1" src="https://www.github.com/" style="display:inline-flex; width:100%; height:140px" nodeintegration></webview>
<script>
var webview = document.getElementById('wv1');
webview.addEventListener('dom-ready', function() {
webview.insertCSS('html,body{ background-color: #FF0000 !important;}')
});
</script>
I am trying to make it so that after the content is loaded in a web browser, the background using CSS is changed to red. Open for any alternatives or help with why the above doesn't work.
thank
+3
source to share
2 answers
It works for me using the following setup, basically just an electronic quick start
Running from electron index.js
index.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
const url = require('url')
let win
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.webContents.openDevTools()
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
index.html
<webview id="wv1" src="https://www.github.com/" style="display:inline-flex; width:100%; height:140px" nodeintegration></webview>
<script>
var webview = document.getElementById('wv1');
webview.addEventListener('dom-ready', function () {
webview.insertCSS('html,body{ background-color: #FF0000 !important;}')
});
</script>
+2
source to share
To make sure you can use instaed dom-ready DOMContentLoaded and insertCss instead of insertRule.
var webview = document.getElementById('wv1');
webview.addEventListener('DOMContentLoaded', function() {
webview.insertRule('html,body{ background-color: #FF0000 !important;}',1)
});
However, if it doesn't work, you can try
webview.querySelector(body) !== null
Inside the function.
hope it works.
+1
source to share