Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject CSS into <webview> Chrome/Electron/HTML/CSS/JS

Can anyone tell me why the below wont work? Please forgive any mistakes I am 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'm trying to get it so that once the content within the webview has loaded the background is changed to red via CSS. Open to any alternatives or help with why the above wont work.

thanks

like image 562
user3236169 Avatar asked Mar 21 '17 14:03

user3236169


Video Answer


2 Answers

It works for me using the following setup, basically just the electron quick start

Run as electron index.js

Result

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>
like image 102
E. Sundin Avatar answered Sep 21 '22 16:09

E. Sundin


Just to be sure you may want to use instead of dom-ready the DOMContentLoaded and instead of insertCss, insertRule.

var webview = document.getElementById('wv1');

webview.addEventListener('DOMContentLoaded', function() {
   webview.insertRule('html,body{ background-color: #FF0000 !important;}',1)
 });

However, if it won't work you may want to try

webview.querySelector(body) !== null

Inside the function.

hope it works.

like image 28
Beni Sinca Avatar answered Sep 21 '22 16:09

Beni Sinca