Search code examples
electron

Electron refuse to load preload.js despite file present and I try to load it by absolutely path


Electron refuse to load preload.js, preload.mjs in any version - if I try to use relative path or absolutely path. I tried all possible configuration, but still failed

    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false, 
        preload: path.resolve(__dirname, '..', '..', 'dist', 'angular-electron1', 'browser', 'preload.mjs'),
        //preload: 'E:\\Angular\\AngularElectron1\\AngularElectron1\\dist\\angular-electron1\\browser\\preload.mjs' 
        //preload: 'E:\\Angular\\AngularElectron1\\AngularElectron1\\dist\\angular-electron1\\browser\\preload.js' 
        },
});

despite file already present

file already present

I have no other idea how to force Electron load my preload.js script. Script present, but Electron refuse to load it. Any ideas, please.


Solution

  • Looks like Electron finds and executes your preload script, but throws an error while executing the script:

    Error: contextBridge API can only be used when contextIsolation is enabled
    

    Seems pretty straightforward to fix: just enable context isolation in your BrowserWindow options.

    Or, alternatively, don't use the contextBridge API in your preload script if context isolation is disabled:

    // preload.ts
    // ...
    
    if (process.contextIsolated) {
      contextBridge.exposeInMainWorld("myAPI", { foo: "bar" });
    } else {
      window.myAPI = { foo: "bar" };
    }