Why is Electron not running my preload script?

Viewed 8345

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.

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'),
Related