Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Electron not running my preload script?

Tags:

electron

I'm trying to use a preload script to work around a CORS header issue in Electron 4.2.3. However, I can't get the preload script to run. A minimal reproduction case:

package.json

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "dependencies": {
    "electron": "^4.2.3"
  }
}

main.js

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

app.on('ready', function() {
  const win = new BrowserWindow({
    webPreferences: {
      preload: `file://${__dirname}/preload.js`,
    }
  })
  win.webContents.openDevTools()
  win.loadFile('index.html')
})

preload.js

window.preloadWasRun = 'preload was run'

index.html

<body>
  <script>
    document.write(window.preloadWasRun || 'preload was not run')
  </script>
</body>

No matter what settings I use for webSecurity, nodeIntegration and contextIsolation, it seems that my preload script is just getting ignored. Even if I make a syntax error in the script, it doesn't show any errors anywhere.

like image 256
Thomas Avatar asked Jun 04 '19 14:06

Thomas


People also ask

How do you preload a script?

The rel="preload" attribute value is used to preload assets. It can be applied to several file formats, including CSS, JS, fonts, images, and more. Depending on the type of file you would like to preload, the corresponding as attribute may also need to be included along with rel="preload" .

What is Nodeintegration electron?

Electron node integration refers to the ability of accessing Node. js resources from within the “renderer” thread (the UI). It is enabled by default in Quasar CLI, although Electron is encouraging developers to turn it off as a security precaution.

What is context isolation electron?

What is it? ​ Context Isolation is a feature that ensures that both your preload scripts and Electron's internal logic run in a separate context to the website you load in a webContents .


1 Answers

Turns out it has to be an absolute path name, not an absolute URL. None of these work:

      preload: `file://${__dirname}/preload.js`,
      preload: './preload.js',
      preload: 'preload.js',

But this works as advertised:

      preload: `${__dirname}/preload.js`,

Since it seems to be a filesystem path rather than a URL, it might also be wise to use path.join instead, to account for platforms with weird path separators:

      preload: path.join(__dirname, 'preload.js'),
like image 151
Thomas Avatar answered Nov 25 '22 11:11

Thomas