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:
- Create a new Blazor Web App, targeting
net10.0
- Add
ElectronNET.Core and ElectronNET.Core.AspNet version 0.4.0 as NuGet packages
- 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();
}
- 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);
}
});
- 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>
- Run the application and try to access
window.electronApi.getPathForFile in JavaScript
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.Preloadoption 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).Steps to Reproduce:
net10.0ElectronNET.CoreandElectronNET.Core.AspNetversion 0.4.0 as NuGet packagesbuilder.UseElectron(args, ElectronAppReady);to the builder call and the following method for creating the window:preload.jsin the root directory of the project with the following content (example from the Electron docs):.csprojfile) to ensure the preload script is copied to the output directory:window.electronApi.getPathForFilein JavaScript