Search code examples
node.jselectronchromiumelectron-builder

How to Inject CSS changes into my Electron js app?


I use loadURL to load the web, I want to make some changes. Is there a way to inject a css snippet once the page is rendered?

There are extensions for chrome that do what I want (like UserCSS), but I understand that they can't be used inside an Electron App.

enter image description here


Solution

  • After your page has completed loading...

    Here is an example of adding CSS:

    // When document has loaded, initialize
    document.onreadystatechange = (event) => {
        if (document.readyState == "complete") {
            // Document has finished loading here
                var styles = `img#license {
                                animation: none;
                                animation-iteration-count: 1;
                                animation-fill-mode: forwards;
                                position: absolute;
                                z-index: 3;
                                width: 375px;
                                top: 204px;
                                left: 112px;
                                visibility: hidden;
                            }`
                var styleSheet = document.createElement("style");
                styleSheet.innerText = styles;
                document.head.appendChild(styleSheet);
        }
    };
    

    I use the above to display a unlicensed image over my Electron app from the preload.js script, as it has access to the document element.

    Edit the CSS to your needs.