Skip to content

Preload Script is Not Loaded #1028

@AeonSake

Description

@AeonSake

I'm trying to expose certain utility functions to the renderer process. Electron advises using a preload script and expose the relevant functions via the contextBridge. Unfortunately, it seems the preload script is not called when specifying the file path via the BrowserWindowOptions.WebPreferences.Preload option during window creation. Furthermore, it seems the preload file is not checked at all because even proving an invalid file path won't lead to an exception (which I somewhat expected in that scenario).

  • NuGet Version: 0.4.0
  • Electron Version: 39.2.6
  • Electron Builder Version: 26.0.12
  • Framework: net10.0
  • Target: win-x64 (specified via publish profile)
  • IDE: Visual Studio 2026 18.1.1

Steps to Reproduce:

  1. Create a new Blazor Web App, targeting net10.0
  2. Add ElectronNET.Core and ElectronNET.Core.AspNet version 0.4.0 as NuGet packages
  3. Add builder.UseElectron(args, ElectronAppReady); to the builder call and the following method for creating the window:
private static async Task ElectronAppReady()
{
    var options = new BrowserWindowOptions
    {
        Show = false,
        IsRunningBlazor = true,
        WebPreferences = new WebPreferences
        {
             Preload = Path.Combine(AppContext.BaseDirectory, "preload.js")
        }
    };
    var browserWindow = await Electron.WindowManager.CreateWindowAsync(options);
    browserWindow.OnReadyToShow += () => browserWindow.Show();
}
  1. Create a file called preload.js in the root directory of the project with the following content (example from the Electron docs):
const { contextBridge, webUtils } = require('electron');

contextBridge.exposeInMainWorld('electronApi', {
    getPathForFile: (file) => {
        return webUtils.getPathForFile(file);
    }
});
  1. Add the following to the project configuration (.csproj file) to ensure the preload script is copied to the output directory:
<ItemGroup>
    <Content Include="preload.js" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
  1. Run the application and try to access window.electronApi.getPathForFile in JavaScript

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions