Electron not loading preload script when application is built

206 Views Asked by At

I am fairly new to Electron and I am having an issue of the preload script after I have built the application (electron-builder). I am upgrading the Electron version to 26.3 from a very old version. The old version was using nodeIntegration = true and contextIsolation = false exposing renderer. I am wanting to use contextBridge to communicate between renderer and Main like mentioned in the documentation. I am setting the preload parameter in the browser window to the path where the preload.js script is located.

webPreferences: {
            webviewTag: true,
            plugins: true,
            contextIsolation: true,
            preload: path.join(__dirname, 'scripts', 'preload.js')
        }

When I run it locally it works, but when I build it it is not loading the script. I realized that the path is different between Local development and when it is built. So I added the preload script to the esxtrResources section of the package.json file.

"build": {
    "extraResources": [
      "./launcher/**",
      "./extraResources/**",
      "./scripts/preload.js"
    ],

I have also tried using "files" parameter in package.json and didn't work either.

"build": {
    "files": [
      "main.js",
      "./scripts/preload.js"
    ],
    "extraResources": [
      "./launcher/**",
      "./extraResources/**"
    ],

When I build the application, I can see that the preload script was put into the resources directory of the application, but when I start the app, I get a white screen. I put in extra logging to see how far I get through the process and I don't see any logs showing the the preload script was loaded. I have also tried several different ways of getting the absolute path but have been unsucsessful.

__dirname
process.cwd()
process.resourcesPath
app.getAppPath()

Can someone please tell me what I'm doing wrong?

1

There are 1 best solutions below

0
On

I figured out what was going on. Once I figured out how to display the dev-tools automatically when Electron loads, I was able to see the error and causing the application not to load. I didn't know the preload script only allows requiring electron module.

const { ipcRenderer, contextBridge } = require('electron');

I found that out as soon as I was able to view the console. I removed all of the other requires I had and the preload script loads correctly. It was a newbie mistake. Wanted to share this in case anybody else runs into this.