0

I'm trying to make a small electron app that loads some random website via 'loadURL' and then dynamically applies scripts and stylesheets to it.

I've made a simple example-app, that loads https://stackoverflow.com/, and in 'preload.js' adds 'renderer.js' and 'styles.css' to the website's DOM. Here is the code:

main.js

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

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.loadURL('https://stackoverflow.com/')
}


app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

preload.js

window.addEventListener('DOMContentLoaded', () => {
    //Dynamic style linking to the document
    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("href", "E:/SomeCodingStuff/testElectron/test/styles.css")
    document.getElementsByTagName("head")[0].appendChild(fileref)
  
    //Dynamic script linking to the document
    var fileref2 = document.createElement("script")
    fileref2.setAttribute("src", "E:/SomeCodingStuff/testElectron/test/renderer.js")
    document.getElementsByTagName("body")[0].appendChild(fileref2)
  })

renderer.js

document.body.classList.add('blue_background');

styles.css

.blue_background{
    background-color: cornflowerblue;
}

As you can see, this app should open a website and change it's body's color to blue - and it works perfectly fine with a local 'index.html' file and 'loadFile', yet with 'loadURL' it refuses to load local resources: screenshot of a console

I found a post about it: Cannot open local file - Chrome: Not allowed to load local resource so I understand that Chrome intentionally refuses to load local files. The solution provided in that post (loading these files using a local server) works fine for me, but it is too bulky and inconvenient for an app I want to make.

It seems like there is no other workaround in classic web-coding, but is there any electron solution to this problem?

Would be grateful for any suggestions!

fegorius
  • 1
  • 2

0 Answers0