diff --git a/Changelog.md b/Changelog.md index 6dc2107e..de45ec39 100644 --- a/Changelog.md +++ b/Changelog.md @@ -9,6 +9,7 @@ - Fixed startup failure with host lockfile (#1125) @DYH1319 - Fixed hanging host when Electron exists before bridge (#1124) @DYH1319 - Fixed dev mode launches passing the script file instead of the app directory (#1121) @Denny09310 +- Added support for `WebContentsView` as an alternative to `BrowserWindow` (#1131) # 0.6.0 diff --git a/src/ElectronNET.Samples.AppIcons/Assets/app.svg b/src/ElectronNET.Samples.AppIcons/Assets/app.svg new file mode 100644 index 00000000..e5a385c2 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Assets/app.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/app.icns b/src/ElectronNET.Samples.AppIcons/Assets/icons/app.icns new file mode 100644 index 00000000..cbf05143 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/app.icns differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/app.ico b/src/ElectronNET.Samples.AppIcons/Assets/icons/app.ico new file mode 100644 index 00000000..1f3e34e3 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/app.ico differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/128x128.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/128x128.png new file mode 100644 index 00000000..e2b83fc4 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/128x128.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/16x16.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/16x16.png new file mode 100644 index 00000000..6fd8daa7 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/16x16.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/24x24.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/24x24.png new file mode 100644 index 00000000..c978b82f Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/24x24.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/256x256.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/256x256.png new file mode 100644 index 00000000..c082ce2e Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/256x256.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/32x32.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/32x32.png new file mode 100644 index 00000000..9453bf9b Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/32x32.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/48x48.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/48x48.png new file mode 100644 index 00000000..c01d5396 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/48x48.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/512x512.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/512x512.png new file mode 100644 index 00000000..8ac3858c Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/512x512.png differ diff --git a/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/64x64.png b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/64x64.png new file mode 100644 index 00000000..b54145c2 Binary files /dev/null and b/src/ElectronNET.Samples.AppIcons/Assets/icons/linux/64x64.png differ diff --git a/src/ElectronNET.Samples.AppIcons/ElectronNET.Samples.AppIcons.csproj b/src/ElectronNET.Samples.AppIcons/ElectronNET.Samples.AppIcons.csproj new file mode 100644 index 00000000..8789805a --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/ElectronNET.Samples.AppIcons.csproj @@ -0,0 +1,46 @@ + + + + net10.0 + enable + enable + false + + Assets\icons\app.ico + + true + + + + + + Electron.NET App Icons Sample + 1.0.0 + com.electronnet.app-icons-sample + Shows how to provide app icons for Windows, Linux and macOS + Electron.NET + Copyright © 2026, Electron.NET + 30.4.0 + MIT + + + + + + + + + + + + + + + + + + + + diff --git a/src/ElectronNET.Samples.AppIcons/Program.cs b/src/ElectronNET.Samples.AppIcons/Program.cs new file mode 100644 index 00000000..2b1809cc --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Program.cs @@ -0,0 +1,54 @@ +using ElectronNET.API; +using ElectronNET.API.Entities; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddElectron(); + +builder.WebHost.UseElectron(args, async () => +{ + // The icons are copied next to the .NET assemblies (see the .csproj), so this works + // both during development and in the packaged app (where the .NET app lives in resources/bin). + var iconsDir = Path.Combine(AppContext.BaseDirectory, "Assets", "icons"); + + var options = new BrowserWindowOptions + { + Width = 800, + Height = 600, + Show = true, + Title = "App Icons Sample", + }; + + if (OperatingSystem.IsWindows()) + { + // Window + taskbar icon. Packaged apps already get the icon from the executable, + // but during development (unpackaged) the default Electron icon would be shown. + options.Icon = Path.Combine(iconsDir, "app.ico"); + options.AutoHideMenuBar = true; + } + else if (OperatingSystem.IsLinux()) + { + // Window icon. Linux has no icon embedded in the executable, so this is also relevant + // for packaged apps (in addition to the icon of the desktop entry). + options.Icon = Path.Combine(iconsDir, "linux", "512x512.png"); + options.AutoHideMenuBar = true; + } + else if (OperatingSystem.IsMacOS()) + { + // macOS windows have no icon. In the packaged app, the dock icon comes from the .icns + // inside the app bundle - but during development (unpackaged) the Electron icon would be + // shown, so we set the dock icon explicitly (harmless for the packaged app). + Electron.Dock.SetIcon(Path.Combine(iconsDir, "linux", "512x512.png")); + } + + var window = await Electron.WindowManager.CreateWindowAsync(options); + + window.OnReadyToShow += () => window.Show(); +}); + +var app = builder.Build(); + +app.UseDefaultFiles(); +app.UseStaticFiles(); + +app.Run(); diff --git a/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/linux-x64.pubxml b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/linux-x64.pubxml new file mode 100644 index 00000000..b455d10c --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/linux-x64.pubxml @@ -0,0 +1,16 @@ + + + + Release + Any CPU + true + FileSystem + publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\ + FileSystem + <_TargetId>Folder + net10.0 + linux-x64 + 7c3e5b1a-4d2f-4e8a-9b6c-1f0a2d3e4c5b + true + + \ No newline at end of file diff --git a/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-arm64.pubxml b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-arm64.pubxml new file mode 100644 index 00000000..0fc6d49b --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-arm64.pubxml @@ -0,0 +1,16 @@ + + + + Release + Any CPU + true + FileSystem + publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\ + FileSystem + <_TargetId>Folder + net10.0 + osx-arm64 + 7c3e5b1a-4d2f-4e8a-9b6c-1f0a2d3e4c5b + true + + \ No newline at end of file diff --git a/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-x64.pubxml b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-x64.pubxml new file mode 100644 index 00000000..2224bb57 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/osx-x64.pubxml @@ -0,0 +1,16 @@ + + + + Release + Any CPU + true + FileSystem + publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\ + FileSystem + <_TargetId>Folder + net10.0 + osx-x64 + 7c3e5b1a-4d2f-4e8a-9b6c-1f0a2d3e4c5b + true + + \ No newline at end of file diff --git a/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/win-x64.pubxml b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/win-x64.pubxml new file mode 100644 index 00000000..02854e78 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/PublishProfiles/win-x64.pubxml @@ -0,0 +1,16 @@ + + + + Release + Any CPU + true + FileSystem + publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\ + FileSystem + <_TargetId>Folder + net10.0 + win-x64 + 7c3e5b1a-4d2f-4e8a-9b6c-1f0a2d3e4c5b + true + + \ No newline at end of file diff --git a/src/ElectronNET.Samples.AppIcons/Properties/electron-builder.json b/src/ElectronNET.Samples.AppIcons/Properties/electron-builder.json new file mode 100644 index 00000000..8e4c9d34 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/electron-builder.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/refs/heads/master/packages/app-builder-lib/scheme.json", + "compression": "maximum", + "win": { + "target": [ + { + "target": "portable", + "arch": "x64" + } + ], + "icon": "bin/Assets/icons/app.ico" + }, + "linux": { + "target": [ + "AppImage", + "tar.xz" + ], + "executableArgs": [ "--no-sandbox" ], + "icon": "bin/Assets/icons/linux", + "category": "Utility", + "artifactName": "${name}-${arch}-${version}.${ext}" + }, + "mac": { + "target": [ + "dmg" + ], + "icon": "bin/Assets/icons/app.icns" + } +} diff --git a/src/ElectronNET.Samples.AppIcons/Properties/launchSettings.json b/src/ElectronNET.Samples.AppIcons/Properties/launchSettings.json new file mode 100644 index 00000000..6d8e62dd --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:0", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/ElectronNET.Samples.AppIcons/README.md b/src/ElectronNET.Samples.AppIcons/README.md new file mode 100644 index 00000000..187d0ea5 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/README.md @@ -0,0 +1,66 @@ +# Electron.NET Sample: App Icons + +A working sample with app icons for all three platforms: Windows, Linux and macOS. + +There are two separate places where icons matter: + +1. **Packaging** — the icon of the executable, installer, app bundle or desktop entry. It is set by electron-builder via `Properties/electron-builder.json`. +2. **Runtime** — the icon of the window, taskbar or dock while the app runs. It is set in `Program.cs`. This matters most during development, because the unpackaged app would otherwise show the default Electron icon. On Linux, it is also needed in the packaged app. + +## Files + +``` +Assets/ +├── app.svg source artwork (not used at runtime) +└── icons/ + ├── app.ico Windows: 16, 24, 32, 48, 64, 128, 256 px + ├── app.icns macOS: 16 to 1024 px (incl. @2x variants) + └── linux/ + ├── 16x16.png Linux: one PNG per size, named x.png + ├── ... + └── 512x512.png +``` + +The `.csproj` copies `Assets/icons` to the build and publish output. During publishing, the .NET app is placed in the `bin` folder of the electron-builder project, so `electron-builder.json` references the icons as `bin/Assets/icons/...`: + +```json +{ + "win": { "icon": "bin/Assets/icons/app.ico" }, + "linux": { "icon": "bin/Assets/icons/linux" }, + "mac": { "icon": "bin/Assets/icons/app.icns" } +} +``` + +`` in the `.csproj` also sets the icon of the .NET executable itself on Windows (e.g., shown in Task Manager). + +## Platform notes + +| Platform | Requirements | +| --- | --- | +| Windows | `.ico` with at least a 256×256 image. Include smaller sizes (16, 32, 48) so that the taskbar and Explorer don't have to scale down. | +| Linux | A folder with `x.png` files, or a single PNG of at least 256×256 px. The icon is only part of formats that have a desktop entry (AppImage, deb, rpm, ...) — a plain `tar.xz` archive has none, so there only the runtime window icon applies. | +| macOS | `.icns` with sizes up to 1024×1024 (512×512@2x). Windows on macOS have no icon, so at runtime only the dock icon can be set (`Electron.Dock.SetIcon`). The modern `.icon` format (Icon Composer) is supported too, see [Configuration](../../docs/Using/Configuration.md#app-icon-path). | + +## Creating your own icons + +Start with a square artwork of 1024×1024 px (e.g., `Assets/app.svg`) and export it into the formats above. For example: + +- **ImageMagick** (`.ico` and PNGs): + ```sh + magick app.svg -background none -define icon:auto-resize=256,128,64,48,32,24,16 app.ico + for s in 16 24 32 48 64 128 256 512; do magick app.svg -background none -resize ${s}x${s} linux/${s}x${s}.png; done + ``` +- **iconutil** on macOS (`.icns` from an `.iconset` folder): + ```sh + iconutil -c icns app.iconset -o app.icns + ``` + +## Run and package + +```sh +# Run during development +dotnet run + +# Create a package, e.g., for Windows (see Properties/PublishProfiles for the others) +dotnet publish /p:PublishProfile=win-x64 +``` diff --git a/src/ElectronNET.Samples.AppIcons/wwwroot/index.html b/src/ElectronNET.Samples.AppIcons/wwwroot/index.html new file mode 100644 index 00000000..edaae167 --- /dev/null +++ b/src/ElectronNET.Samples.AppIcons/wwwroot/index.html @@ -0,0 +1,45 @@ + + + + + + App Icons Sample + + + +

App Icons Sample

+

+ Look at the window, the taskbar / dock and - after packaging - the installer and executable: + they should all show the sample icon instead of the default Electron icon. +

+ + + + + + + + + + + + + + + + + + + + + + +
PlatformPackaged app (electron-builder)Runtime (Program.cs)
WindowsAssets/icons/app.icoWindow icon app.ico
LinuxAssets/icons/linux/*.pngWindow icon linux/512x512.png
macOSAssets/icons/app.icnsDock icon linux/512x512.png
+ + diff --git a/src/ElectronNET.Samples.BlazorServer/Components/App.razor b/src/ElectronNET.Samples.BlazorServer/Components/App.razor new file mode 100644 index 00000000..17595e43 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/App.razor @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + @* A desktop app has no reason to mix render modes: the whole app is interactive (except the error page). *@ + + + + + + +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + private IComponentRenderMode? PageRenderMode => + HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Layout/MainLayout.razor b/src/ElectronNET.Samples.BlazorServer/Components/Layout/MainLayout.razor new file mode 100644 index 00000000..d58f6142 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Layout/MainLayout.razor @@ -0,0 +1,47 @@ +@inherits LayoutComponentBase +@implements IDisposable +@inject AppEvents Events +@inject NavigationManager Navigation +@inject WindowService Window + +
+ + +
+ @Body +
+
+ +
+ An unhandled error has occurred. + Reload + 🗙 +
+ +@code { + protected override void OnInitialized() + { + // Electron -> Blazor: the application menu asks for navigation (see Desktop/ElectronStartup.cs). + Events.NavigationRequested += OnNavigationRequested; + } + + private void OnNavigationRequested(string uri) + { + // The event is raised on an Electron.NET thread - switch to this circuit's renderer first. + _ = InvokeAsync(() => Navigation.NavigateTo(uri)); + } + + public void Dispose() + { + Events.NavigationRequested -= OnNavigationRequested; + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/Error.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Error.razor new file mode 100644 index 00000000..e5eeddf9 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Error.razor @@ -0,0 +1,37 @@ +@page "/Error" +@using System.Diagnostics +@attribute [ExcludeFromInteractiveRouting] + +Error + +

Error.

+

An error occurred while processing your request.

+ +@if (ShowRequestId) +{ +

+ Request ID: @RequestId +

+} + +

Development Mode

+

+ Swapping to Development environment will display more detailed information about the error that occurred. +

+

+ The Development environment shouldn't be enabled for deployed applications. + It can result in displaying sensitive information from exceptions to end users. + For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development + and restarting the app. +

+ +@code{ + [CascadingParameter] + private HttpContext? HttpContext { get; set; } + + private string? RequestId { get; set; } + private bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + + protected override void OnInitialized() => + RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier; +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/Home.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Home.razor new file mode 100644 index 00000000..57812560 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Home.razor @@ -0,0 +1,54 @@ +@page "/" + +Home + +

Blazor Server + Electron.NET

+ +

+ This sample shows how to structure a Blazor Server app that runs in Electron, and how the different parts work together. + Everything below runs in a single .NET process: +

+ +
+
+

Interactivity

+

+ Plain Blazor: components handle events and re-render via the SignalR connection to the Electron window. + JS interop covers what only the browser can do. Nothing here depends on Electron. +

+

Components/Pages/Interactivity.razor

+
+
+

Window Control

+

+ Components control the Electron window through WindowService, and window events + (focus, maximize) flow back into the UI through AppEvents. +

+

Desktop/WindowService.cs

+
+
+

Native Capabilities

+

+ Native dialogs, notifications, clipboard and shell via NativeService. + Files are read directly by .NET - no detour through the renderer. +

+

Desktop/NativeService.cs

+
+
+ +

How it fits together

+
+ Electron window (renderer)          .NET process
+┌──────────────────────────┐        ┌───────────────────────────────────────────────┐
+│ HTML rendered by Blazor  │◄──────►│ Components (Pages, Layout)                    │
+│ blazor.web.js            │ SignalR│   │ inject                     ▲ subscribe    │
+└──────────────────────────┘        │   ▼                            │              │
+                                    │ WindowService / NativeService  AppEvents      │
+ Electron main process              │   │ Electron.*                 ▲              │
+┌──────────────────────────┐        │   ▼                            │              │
+│ windows, menus, dialogs, │◄──────►│ Electron.NET API ──── events ──┘              │
+│ notifications, ...       │ socket │ (ElectronStartup: window + application menu)  │
+└──────────────────────────┘        └───────────────────────────────────────────────┘
+
+ +

Try the application menu (e.g., Ctrl/Cmd + 2): the click is handled in .NET and turned into a Blazor navigation.

diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/Interactivity.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Interactivity.razor new file mode 100644 index 00000000..cf92e089 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Interactivity.razor @@ -0,0 +1,84 @@ +@page "/interactivity" +@implements IAsyncDisposable +@inject IJSRuntime JS + +Interactivity + +

Interactivity

+ +

+ This page is plain Blazor and works the same in Electron and in a browser. Event handlers run in .NET; + Blazor sends the resulting DOM changes to the window. +

+ +
+

Events and data binding

+

+ +

+

+ + @if (!string.IsNullOrWhiteSpace(name)) + { + Hello, @name! + } +

+
+ +
+

JavaScript interop

+

+ Some information only exists in the page. A small JS module (wwwroot/js/interop.js) is loaded + with JS interop to read it. +

+

+ +

+ @if (viewport is not null) + { +

Viewport: @viewport.Width × @viewport.Height px, device pixel ratio @viewport.PixelRatio, user agent:

+
@viewport.UserAgent
+ } +
+ +@code { + private int count; + private string? name; + private IJSObjectReference? module; + private ViewportInfo? viewport; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + // JS interop is only possible once the component is rendered interactively. + if (firstRender) + { + module = await JS.InvokeAsync("import", "./js/interop.js"); + StateHasChanged(); + } + } + + private async Task ReadViewportAsync() + { + if (module is not null) + { + viewport = await module.InvokeAsync("getViewportInfo"); + } + } + + public async ValueTask DisposeAsync() + { + if (module is not null) + { + try + { + await module.DisposeAsync(); + } + catch (JSDisconnectedException) + { + // The window was closed or reloaded - nothing to clean up. + } + } + } + + private sealed record ViewportInfo(int Width, int Height, double PixelRatio, string UserAgent); +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/Native.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Native.razor new file mode 100644 index 00000000..55e7050a --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/Native.razor @@ -0,0 +1,120 @@ +@page "/native" +@inject NativeService Native + +Native Capabilities + +

Native Capabilities

+ +@if (!Native.IsAvailable) +{ +

Not running in Electron - native capabilities are not available in a browser.

+} +else if (electronVersion is not null) +{ +

Electron @electronVersion

+} + +
+

Open a file

+

+ Electron shows the native dialog and returns the path. The file is then read by .NET with File.ReadAllTextAsync - + Blazor Server code already runs with full access to the file system. +

+

+ + @if (file is not null) + { + + } +

+ @if (file is not null) + { +

@file.Value.Path (@file.Value.Content.Length characters)

+
@Preview(file.Value.Content)
+ } +
+ +
+

Dialogs and notifications

+

+ + +

+ @if (status is not null) + { +

@status

+ } +
+ +
+

Clipboard and shell

+

+ + + +

+

+ +

+
+ +@code { + private string? electronVersion; + private (string Path, string Content)? file; + private string? status; + private string clipboardText = "Copied from Blazor"; + + protected override async Task OnInitializedAsync() + { + if (Native.IsAvailable) + { + electronVersion = await Native.GetElectronVersionAsync(); + } + } + + private async Task OpenFileAsync() + { + try + { + file = await Native.PickTextFileAsync() ?? file; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + status = $"Could not read the file: {ex.Message}"; + } + } + + private Task ShowInFolderAsync() => + file is { } f ? Native.ShowInFolderAsync(f.Path) : Task.CompletedTask; + + private async Task ConfirmAsync() + { + var confirmed = await Native.ConfirmAsync("Do you like this sample?", "The answer is handled in a Blazor component."); + status = confirmed ? "Thanks! 🎉" : "Let us know what's missing on GitHub."; + } + + private void Notify() + { + Native.ShowNotification("Hello from Blazor", "Click this notification.", onClick: () => + { + // Raised on an Electron.NET thread: re-render via InvokeAsync. + _ = InvokeAsync(() => + { + status = $"The notification was clicked at {DateTime.Now:T}."; + StateHasChanged(); + }); + }); + + status = "Notification shown."; + } + + private async Task PasteAsync() + { + clipboardText = await Native.ReadClipboardAsync(); + } + + private static string Preview(string content) => + content.Length > 5000 ? content[..5000] + "\n…" : content; +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/NotFound.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/NotFound.razor new file mode 100644 index 00000000..e9b4bb7a --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/NotFound.razor @@ -0,0 +1,6 @@ +@page "/not-found" + +Not Found + +

Not Found

+

Sorry, the content you are looking for does not exist.

diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Pages/WindowControl.razor b/src/ElectronNET.Samples.BlazorServer/Components/Pages/WindowControl.razor new file mode 100644 index 00000000..b6a48ef3 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Pages/WindowControl.razor @@ -0,0 +1,83 @@ +@page "/window" +@implements IDisposable +@inject WindowService Window +@inject AppEvents Events + +Window Control + +

Window Control

+ +@if (!Window.IsAvailable) +{ +

Not running in Electron - the window cannot be controlled from a browser.

+} + +
+

Blazor → Electron

+

The buttons call WindowService, which uses the Electron.NET BrowserWindow API.

+ +

+ + +

+

+ + + +

+

+ + +

+
+ +
+

Electron → Blazor

+

+ Window events are forwarded through AppEvents. Maximize the window with its title bar, + or click into another app, and watch this table update. +

+ + + + + +
Maximized@Window.IsMaximized
Focused@Window.IsFocused
Always on top@Window.IsAlwaysOnTop
Events received@eventCount
+
+ +@code { + private string title = "Blazor Server Sample"; + private int progress; + private int eventCount; + + protected override void OnInitialized() + { + Events.WindowStateChanged += OnWindowStateChanged; + } + + private void OnWindowStateChanged() + { + // Raised on an Electron.NET thread: re-render via InvokeAsync. + _ = InvokeAsync(() => + { + eventCount++; + StateHasChanged(); + }); + } + + private void UpdateProgress() => Window.SetProgress(progress / 100.0); + + private void ClearProgress() + { + progress = 0; + Window.SetProgress(-1); + } + + public void Dispose() + { + Events.WindowStateChanged -= OnWindowStateChanged; + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/Components/Routes.razor b/src/ElectronNET.Samples.BlazorServer/Components/Routes.razor new file mode 100644 index 00000000..ebc312be --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/Routes.razor @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ElectronNET.Samples.BlazorServer/Components/_Imports.razor b/src/ElectronNET.Samples.BlazorServer/Components/_Imports.razor new file mode 100644 index 00000000..47f76df9 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Components/_Imports.razor @@ -0,0 +1,9 @@ +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.JSInterop +@using ElectronNET.Samples.BlazorServer +@using ElectronNET.Samples.BlazorServer.Components +@using ElectronNET.Samples.BlazorServer.Components.Layout +@using ElectronNET.Samples.BlazorServer.Desktop diff --git a/src/ElectronNET.Samples.BlazorServer/Desktop/AppEvents.cs b/src/ElectronNET.Samples.BlazorServer/Desktop/AppEvents.cs new file mode 100644 index 00000000..989985c3 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Desktop/AppEvents.cs @@ -0,0 +1,27 @@ +namespace ElectronNET.Samples.BlazorServer.Desktop; + +/// +/// Carries events from the Electron side (menus, window events, ...) to the Blazor UI. +/// +/// +/// Electron callbacks (e.g., a menu click) run outside of any Blazor circuit. They cannot +/// use a component's NavigationManager or call StateHasChanged directly. Instead, they raise +/// an event on this singleton, and the components that are interested subscribe to it and +/// marshal back onto their renderer with InvokeAsync. +/// +public sealed class AppEvents +{ + /// + /// Raised when something outside the UI (e.g., the application menu) wants to navigate. + /// + public event Action? NavigationRequested; + + /// + /// Raised when the state of the main window changed (maximized, focused, ...). + /// + public event Action? WindowStateChanged; + + public void RequestNavigation(string uri) => NavigationRequested?.Invoke(uri); + + public void NotifyWindowStateChanged() => WindowStateChanged?.Invoke(); +} diff --git a/src/ElectronNET.Samples.BlazorServer/Desktop/ElectronStartup.cs b/src/ElectronNET.Samples.BlazorServer/Desktop/ElectronStartup.cs new file mode 100644 index 00000000..0845d873 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Desktop/ElectronStartup.cs @@ -0,0 +1,105 @@ +using ElectronNET.API; +using ElectronNET.API.Entities; + +namespace ElectronNET.Samples.BlazorServer.Desktop; + +/// +/// Everything that happens on the Electron side when the app starts: main window and application menu. +/// +public static class ElectronStartup +{ + public static async Task CreateMainWindowAsync(IServiceProvider services) + { + var events = services.GetRequiredService(); + var windowService = services.GetRequiredService(); + + var options = new BrowserWindowOptions + { + Title = "Blazor Server Sample", + Width = 1200, + Height = 800, + MinWidth = 640, + MinHeight = 480, + Show = false, + + // Required for Blazor: injects a preload script that hides Node.js' `module` and `process` + // globals, which would otherwise confuse Blazor's JavaScript. + IsRunningBlazor = true, + }; + + var window = await Electron.WindowManager.CreateWindowAsync(options); + + window.OnReadyToShow += () => window.Show(); + + // Hand the window to the service that the Blazor components use for "Electron control". + windowService.Attach(window); + + Electron.Menu.SetApplicationMenu(CreateMenu(events)); + } + + private static MenuItem[] CreateMenu(AppEvents events) + { + // Menu clicks arrive in .NET outside of any Blazor circuit, + // so we route them through AppEvents (see MainLayout.razor). + MenuItem Page(string label, string uri, string accelerator) => new() + { + Label = label, + Accelerator = accelerator, + Click = () => events.RequestNavigation(uri), + }; + + var menu = new List(); + + if (OperatingSystem.IsMacOS()) + { + menu.Add(new MenuItem { Role = MenuRole.appMenu }); + } + + menu.Add(new MenuItem + { + Label = "File", + Submenu = + [ + Page("Open Text File...", "/native", "CmdOrCtrl+O"), + new MenuItem { Type = MenuType.separator }, + new MenuItem { Role = MenuRole.quit }, + ], + }); + + // Without the edit menu, shortcuts such as Ctrl+C / Ctrl+V do not work in text inputs on macOS. + menu.Add(new MenuItem { Role = MenuRole.editMenu }); + + menu.Add(new MenuItem + { + Label = "View", + Submenu = + [ + Page("Home", "/", "CmdOrCtrl+1"), + Page("Interactivity", "/interactivity", "CmdOrCtrl+2"), + Page("Window Control", "/window", "CmdOrCtrl+3"), + Page("Native Capabilities", "/native", "CmdOrCtrl+4"), + new MenuItem { Type = MenuType.separator }, + new MenuItem { Role = MenuRole.reload }, + new MenuItem { Role = MenuRole.toggleDevTools }, + new MenuItem { Role = MenuRole.togglefullscreen }, + ], + }); + + menu.Add(new MenuItem { Role = MenuRole.windowMenu }); + + menu.Add(new MenuItem + { + Label = "Help", + Submenu = + [ + new MenuItem + { + Label = "Electron.NET on GitHub", + Click = () => Electron.Shell.OpenExternalAsync("https://github.com/ElectronNET/Electron.NET"), + }, + ], + }); + + return [.. menu]; + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/Desktop/NativeService.cs b/src/ElectronNET.Samples.BlazorServer/Desktop/NativeService.cs new file mode 100644 index 00000000..f9fbb70c --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Desktop/NativeService.cs @@ -0,0 +1,88 @@ +using ElectronNET.API; +using ElectronNET.API.Entities; + +namespace ElectronNET.Samples.BlazorServer.Desktop; + +/// +/// Native capabilities: OS features that a web page alone cannot use. +/// +/// +/// Note how the work is split: Electron shows the native dialog and only returns a path, while the +/// file itself is read by .NET. With Blazor Server the UI code already runs in the .NET process, +/// so there is no need to send file contents through Electron. +/// +public sealed class NativeService +{ + public bool IsAvailable => HybridSupport.IsElectronActive; + + /// + /// Opens a native "Open file" dialog and reads the chosen text file. Returns null when canceled. + /// + public async Task<(string Path, string Content)?> PickTextFileAsync() + { + var window = Electron.WindowManager.BrowserWindows.FirstOrDefault(); + + if (window is null) + { + return null; + } + + var files = await Electron.Dialog.ShowOpenDialogAsync(window, new OpenDialogOptions + { + Title = "Open a text file", + Properties = [OpenDialogProperty.openFile], + Filters = + [ + new FileFilter { Name = "Text files", Extensions = ["txt", "md", "json", "log", "csv"] }, + new FileFilter { Name = "All files", Extensions = ["*"] }, + ], + }); + + if (files is not { Length: > 0 }) + { + return null; + } + + var path = files[0]; + var content = await File.ReadAllTextAsync(path); + return (path, content); + } + + public async Task ConfirmAsync(string message, string detail) + { + var window = Electron.WindowManager.BrowserWindows.FirstOrDefault(); + + if (window is null) + { + return false; + } + + var result = await Electron.Dialog.ShowMessageBoxAsync(window, new MessageBoxOptions(message) + { + Type = MessageBoxType.question, + Title = "Please confirm", + Detail = detail, + Buttons = ["Yes", "No"], + }); + + return result.Response == 0; + } + + public void ShowNotification(string title, string body, Action? onClick = null) + { + Electron.Notification.Show(new NotificationOptions(title, body) + { + OnClick = onClick, + }); + } + + public void CopyToClipboard(string text) => Electron.Clipboard.WriteText(text); + + public Task ReadClipboardAsync() => Electron.Clipboard.ReadTextAsync(); + + public Task OpenExternalAsync(string url) => Electron.Shell.OpenExternalAsync(url); + + public Task ShowInFolderAsync(string path) => Electron.Shell.ShowItemInFolderAsync(path); + + public async Task GetElectronVersionAsync() => (await Electron.Process.VersionsAsync).Electron; +} diff --git a/src/ElectronNET.Samples.BlazorServer/Desktop/WindowService.cs b/src/ElectronNET.Samples.BlazorServer/Desktop/WindowService.cs new file mode 100644 index 00000000..739c62ed --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Desktop/WindowService.cs @@ -0,0 +1,78 @@ +using ElectronNET.API; + +namespace ElectronNET.Samples.BlazorServer.Desktop; + +/// +/// Electron control: everything the UI may do with the main window. +/// +/// +/// Components only talk to this service - never to Electron.* directly. This keeps the +/// Electron specifics in one place and lets the UI work (with reduced functionality) when the app +/// is opened in a normal browser, where is false. +/// +public sealed class WindowService(AppEvents events) +{ + private BrowserWindow? window; + + public bool IsAvailable => this.window is not null; + + public bool IsMaximized { get; private set; } + + public bool IsFocused { get; private set; } = true; + + public bool IsAlwaysOnTop { get; private set; } + + /// + /// Called once by after the main window was created. + /// + public void Attach(BrowserWindow mainWindow) + { + this.window = mainWindow; + + // Electron -> .NET: keep our state in sync and forward it to the UI. + mainWindow.OnMaximize += () => this.Update(() => this.IsMaximized = true); + mainWindow.OnUnmaximize += () => this.Update(() => this.IsMaximized = false); + mainWindow.OnFocus += () => this.Update(() => this.IsFocused = true); + mainWindow.OnBlur += () => this.Update(() => this.IsFocused = false); + mainWindow.OnClosed += () => this.window = null; + } + + public void SetTitle(string title) => this.window?.SetTitle(title); + + public void Minimize() => this.window?.Minimize(); + + public void ToggleMaximize() + { + if (this.IsMaximized) + { + this.window?.Unmaximize(); + } + else + { + this.window?.Maximize(); + } + } + + public void ToggleAlwaysOnTop() + { + if (this.window is null) + { + return; + } + + this.IsAlwaysOnTop = !this.IsAlwaysOnTop; + this.window.SetAlwaysOnTop(this.IsAlwaysOnTop); + events.NotifyWindowStateChanged(); + } + + /// + /// Shows progress in the taskbar (Windows / Linux) or dock (macOS). Use a negative value to remove it. + /// + public void SetProgress(double progress) => this.window?.SetProgressBar(progress); + + private void Update(Action change) + { + change(); + events.NotifyWindowStateChanged(); + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/ElectronNET.Samples.BlazorServer.csproj b/src/ElectronNET.Samples.BlazorServer/ElectronNET.Samples.BlazorServer.csproj new file mode 100644 index 00000000..ef4a6229 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/ElectronNET.Samples.BlazorServer.csproj @@ -0,0 +1,38 @@ + + + + net10.0 + enable + enable + true + + true + + + + + + Electron.NET Blazor Server Sample + 1.0.0 + com.electronnet.blazor-server-sample + Shows how to structure a Blazor Server app with Electron.NET + Electron.NET + Copyright © 2026, Electron.NET + 30.4.0 + MIT + true + + + + + + + + + + + + + + + diff --git a/src/ElectronNET.Samples.BlazorServer/Program.cs b/src/ElectronNET.Samples.BlazorServer/Program.cs new file mode 100644 index 00000000..5b38af4c --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Program.cs @@ -0,0 +1,37 @@ +using ElectronNET.API; +using ElectronNET.Samples.BlazorServer.Components; +using ElectronNET.Samples.BlazorServer.Desktop; + +var builder = WebApplication.CreateBuilder(args); + +// UI: Blazor with interactive server rendering. The components run in this .NET process and +// talk to the page in the Electron window via a SignalR connection. +builder.Services.AddRazorComponents() + .AddInteractiveServerComponents(); + +// Desktop: the bridge between the Blazor UI and Electron. +// Singletons, because there is one Electron main process (and one main window) per app. +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +builder.Services.AddElectron(); + +// Called with the app's service provider once Electron is ready: creates the window and menu. +builder.UseElectron(args, ElectronStartup.CreateMainWindowAsync); + +var app = builder.Build(); + +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Error", createScopeForErrors: true); +} + +app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); +app.UseAntiforgery(); + +app.MapStaticAssets(); +app.MapRazorComponents() + .AddInteractiveServerRenderMode(); + +app.Run(); diff --git a/src/ElectronNET.Samples.BlazorServer/Properties/electron-builder.json b/src/ElectronNET.Samples.BlazorServer/Properties/electron-builder.json new file mode 100644 index 00000000..41f483cc --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Properties/electron-builder.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/refs/heads/master/packages/app-builder-lib/scheme.json", + "compression": "maximum", + "linux": { + "target": [ + "tar.xz" + ], + "executableArgs": [ "--no-sandbox" ], + "artifactName": "${name}-${arch}-${version}.${ext}" + }, + "win": { + "target": [ + { + "target": "portable", + "arch": "x64" + } + ] + } +} \ No newline at end of file diff --git a/src/ElectronNET.Samples.BlazorServer/Properties/launchSettings.json b/src/ElectronNET.Samples.BlazorServer/Properties/launchSettings.json new file mode 100644 index 00000000..6d8e62dd --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:0", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/README.md b/src/ElectronNET.Samples.BlazorServer/README.md new file mode 100644 index 00000000..7da22a44 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/README.md @@ -0,0 +1,70 @@ +# Electron.NET Sample: Blazor Server + +This sample shows how to structure a Blazor Server app with Electron.NET, and how the different parts come together: + +- **Client-side interactivity** — regular Blazor components and JS interop +- **Electron control** — controlling the window from components, and reacting to window events +- **Native capabilities** — dialogs, notifications, clipboard, shell + +## Structure + +``` +Program.cs ASP.NET Core + Blazor + Electron.NET setup +Desktop/ Everything Electron-specific +├── ElectronStartup.cs creates the main window and the application menu +├── WindowService.cs Electron control (BrowserWindow API) + window state +├── NativeService.cs native capabilities (dialogs, notifications, clipboard, shell) +└── AppEvents.cs events from Electron to the Blazor UI (menu clicks, window events) +Components/ +├── App.razor root document, global InteractiveServer render mode +├── Layout/MainLayout.razor navigation; handles navigation requests from the menu +└── Pages/ + ├── Interactivity.razor plain Blazor + JS interop (no Electron involved) + ├── WindowControl.razor uses WindowService, listens to AppEvents + └── Native.razor uses NativeService +wwwroot/ CSS and the JS interop module +``` + +## Key points + +### 1. Keep Electron out of the components + +Components never call `Electron.*` directly. They inject `WindowService` / `NativeService` instead. This keeps the Electron-specific code in one place and makes it obvious which parts of the UI need Electron. Both services expose `IsAvailable`, so the app still works (with reduced functionality) when opened in a normal browser. That can be useful for UI development. + +### 2. Calls from Blazor to Electron are just .NET calls + +With Blazor Server, the component code runs in the same .NET process as the Electron.NET API. There is no extra IPC layer to build: a click handler can call `Electron.Dialog.ShowOpenDialogAsync(...)` (through the service) and then read the file with `File.ReadAllTextAsync`. + +### 3. Events from Electron to Blazor go through a singleton + +Electron callbacks, such as menu clicks, window events or notification clicks, run on an Electron.NET thread outside of any Blazor circuit. To get them into the UI: + +1. A singleton (`AppEvents`) raises a .NET event. +2. Components subscribe in `OnInitialized` and unsubscribe in `Dispose`. +3. Handlers switch to the component's renderer with `InvokeAsync(...)` before touching state, calling `StateHasChanged` or navigating. + +`MainLayout.razor` uses this to turn application menu clicks into Blazor navigation. `WindowControl.razor` uses it to show live window state. + +### 4. Blazor-specific window options + +```csharp +var options = new BrowserWindowOptions +{ + Show = false, // show only after the first render, see OnReadyToShow + IsRunningBlazor = true, // hides Node.js globals that would break blazor.web.js +}; +``` + +### 5. Render mode + +A desktop app has no reason to mix render modes, so `App.razor` makes the whole app interactive (`InteractiveServer`). Only the error page opts out with `[ExcludeFromInteractiveRouting]`. + +### 6. Edit menu + +When you replace the default application menu, include the `editMenu` role. Otherwise copy and paste shortcuts don't work in text inputs on macOS. + +## Run + +```sh +dotnet run +``` diff --git a/src/ElectronNET.Samples.BlazorServer/appsettings.Development.json b/src/ElectronNET.Samples.BlazorServer/appsettings.Development.json new file mode 100644 index 00000000..8d7e2b81 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/appsettings.Development.json @@ -0,0 +1,13 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.AspNetCore.SignalR": "Warning", + "Microsoft.AspNetCore.Http.Connections": "Warning", + "Microsoft.AspNetCore.Watch": "Warning", + "Microsoft.AspNetCore.Watch.BrowserRefresh": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/src/ElectronNET.Samples.BlazorServer/appsettings.json b/src/ElectronNET.Samples.BlazorServer/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/src/ElectronNET.Samples.BlazorServer/wwwroot/app.css b/src/ElectronNET.Samples.BlazorServer/wwwroot/app.css new file mode 100644 index 00000000..89287045 --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/wwwroot/app.css @@ -0,0 +1,157 @@ +:root { + color-scheme: light dark; + --accent: #4f46e5; + --border: #8884; + --muted: #8881; + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + line-height: 1.5; +} + +html, body { + margin: 0; + height: 100%; +} + +.page { + display: flex; + min-height: 100vh; +} + +.sidebar { + display: flex; + flex-direction: column; + gap: 0.25rem; + width: 220px; + flex-shrink: 0; + padding: 1rem; + box-sizing: border-box; + background: linear-gradient(160deg, #4f46e5, #06b6d4); + color: #fff; +} + +.sidebar .brand { + font-weight: 600; + font-size: 1.1rem; + margin-bottom: 1rem; +} + +.sidebar a { + color: #fff; + text-decoration: none; + padding: 0.4rem 0.6rem; + border-radius: 6px; +} + +.sidebar a:hover { + background: #fff2; +} + +.sidebar a.active { + background: #fff3; + font-weight: 600; +} + +.sidebar-footer { + margin-top: auto; + font-size: 0.85rem; + opacity: 0.85; +} + +.content { + flex: 1; + padding: 1.5rem 2rem; + max-width: 960px; +} + +h1:focus { + outline: none; +} + +section, .card { + margin: 1rem 0; + padding: 1rem; + border: 1px solid var(--border); + border-radius: 8px; +} + +section h2, .card h2 { + margin-top: 0; + font-size: 1.1rem; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 1rem; +} + +.card { + margin: 0; +} + +.card a { + color: var(--accent); +} + +button { + padding: 0.35rem 0.8rem; + margin-right: 0.25rem; +} + +pre { + background: var(--muted); + padding: 0.75rem; + border-radius: 6px; + overflow: auto; +} + +pre.diagram { + font-size: 0.8rem; + line-height: 1.25; +} + +pre.file-content { + max-height: 320px; +} + +table { + border-collapse: collapse; +} + +th, td { + text-align: left; + padding: 0.3rem 1rem 0.3rem 0; +} + +.notice { + padding: 0.5rem 0.75rem; + border-radius: 6px; + background: #f59e0b33; +} + +.status { + padding: 0.5rem 0.75rem; + border-radius: 6px; + background: #2e7d3233; +} + +#blazor-error-ui { + display: none; + position: fixed; + bottom: 0; + left: 0; + width: 100%; + box-sizing: border-box; + padding: 0.6rem 1.25rem; + background: lightyellow; + color: #000; + box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); + z-index: 1000; +} + +#blazor-error-ui .dismiss { + cursor: pointer; + position: absolute; + right: 0.75rem; + top: 0.5rem; +} diff --git a/src/ElectronNET.Samples.BlazorServer/wwwroot/js/interop.js b/src/ElectronNET.Samples.BlazorServer/wwwroot/js/interop.js new file mode 100644 index 00000000..22ef2e0a --- /dev/null +++ b/src/ElectronNET.Samples.BlazorServer/wwwroot/js/interop.js @@ -0,0 +1,9 @@ +// Loaded on demand by Components/Pages/Interactivity.razor via JS interop. +export function getViewportInfo() { + return { + width: window.innerWidth, + height: window.innerHeight, + pixelRatio: window.devicePixelRatio, + userAgent: navigator.userAgent, + }; +} diff --git a/src/ElectronNET.Samples.PreloadScript/ElectronNET.Samples.PreloadScript.csproj b/src/ElectronNET.Samples.PreloadScript/ElectronNET.Samples.PreloadScript.csproj new file mode 100644 index 00000000..3ff00bba --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/ElectronNET.Samples.PreloadScript.csproj @@ -0,0 +1,43 @@ + + + + net10.0 + enable + enable + false + + true + + + + + + Electron.NET Preload Script Sample + 1.0.0 + com.electronnet.preload-script-sample + Shows how to inject a preload script and use it for IPC between the web content and the .NET app + Electron.NET + Copyright © 2026, Electron.NET + 30.4.0 + MIT + + + + + + + + + + + + + + + + + + + + diff --git a/src/ElectronNET.Samples.PreloadScript/Preload/preload.js b/src/ElectronNET.Samples.PreloadScript/Preload/preload.js new file mode 100644 index 00000000..80ccd70e --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/Preload/preload.js @@ -0,0 +1,35 @@ +// This script runs in the renderer process *before* the web page is loaded. +// +// Because the window is created with `contextIsolation: true` and `sandbox: true`, the page +// itself cannot reach Node.js or Electron. The preload script is the only place where +// `ipcRenderer` is available - and with `contextBridge` we decide exactly which capabilities +// the page gets. Never expose `ipcRenderer` itself; expose small, purpose-built functions. + +const { contextBridge, ipcRenderer } = require("electron"); + +function subscribe(channel, callback) { + // Strip the IpcRendererEvent - it should not leak into the page. + const listener = (_event, ...args) => callback(...args); + ipcRenderer.on(channel, listener); + + // Return an unsubscribe function. + return () => ipcRenderer.removeListener(channel, listener); +} + +contextBridge.exposeInMainWorld("dotnet", { + // page -> .NET (fire and forget), handled by Electron.IpcMain.On("greet", ...) + greet: (name) => ipcRenderer.send("greet", name), + + // page -> .NET -> page (request / response), handled by Electron.IpcMain.Handle(...) + getRuntimeInfo: () => ipcRenderer.invoke("get-runtime-info"), + add: (a, b) => ipcRenderer.invoke("add", { a, b }), + + // .NET -> page, sent via Electron.IpcMain.Send(window, ...) + onGreeting: (callback) => subscribe("greeting", callback), + onClock: (callback) => subscribe("clock", callback), +}); + +// The preload script can also prepare the page directly, e.g., once the DOM is available. +window.addEventListener("DOMContentLoaded", () => { + document.documentElement.dataset.preloaded = "true"; +}); diff --git a/src/ElectronNET.Samples.PreloadScript/Program.cs b/src/ElectronNET.Samples.PreloadScript/Program.cs new file mode 100644 index 00000000..50297825 --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/Program.cs @@ -0,0 +1,102 @@ +using System.Runtime.InteropServices; +using ElectronNET.API; +using ElectronNET.API.Entities; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddElectron(); + +builder.WebHost.UseElectron(args, async () => +{ + // 1. Register the IPC endpoints *before* the window loads, so the page can use them right away. + await RegisterIpcHandlersAsync(); + + // 2. Create the window and inject the preload script. + // Electron loads the preload script from disk, so we need an absolute path. The script is + // copied to the output directory by the .csproj, i.e., it sits next to the .NET assemblies. + var preloadPath = Path.Combine(AppContext.BaseDirectory, "Preload", "preload.js"); + + var options = new BrowserWindowOptions + { + Width = 900, + Height = 700, + Show = false, + WebPreferences = new WebPreferences + { + Preload = preloadPath, + + // Secure defaults: the web content has no access to Node.js or Electron. + // Everything it may do is exposed explicitly by the preload script via contextBridge. + NodeIntegration = false, + ContextIsolation = true, + Sandbox = true, + }, + }; + + if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()) + { + options.AutoHideMenuBar = true; + } + + var window = await Electron.WindowManager.CreateWindowAsync(options); + + window.OnReadyToShow += () => window.Show(); + + // 3. Push messages from .NET to the web content. + StartClock(window); +}); + +var app = builder.Build(); + +app.UseDefaultFiles(); +app.UseStaticFiles(); + +app.Run(); + +static async Task RegisterIpcHandlersAsync() +{ + // Fire-and-forget message (ipcRenderer.send) which we answer with a message of our own (webContents.send). + await Electron.IpcMain.On("greet", payload => + { + var name = payload as string; + var greeting = string.IsNullOrWhiteSpace(name) + ? "Hello, anonymous!" + : $"Hello, {name}! This greeting was created in .NET."; + + var window = Electron.WindowManager.BrowserWindows.FirstOrDefault(); + + if (window is not null) + { + Electron.IpcMain.Send(window, "greeting", greeting); + } + }); + + // Request / response (ipcRenderer.invoke). The return value resolves the promise in the renderer. + Electron.IpcMain.Handle("get-runtime-info", _ => new + { + Framework = RuntimeInformation.FrameworkDescription, + Os = RuntimeInformation.OSDescription, + Architecture = RuntimeInformation.ProcessArchitecture.ToString(), + ProcessId = Environment.ProcessId, + MachineName = Environment.MachineName, + }); + + // Request / response with an argument. Objects arrive as Dictionary. + Electron.IpcMain.Handle("add", payload => + { + if (payload is Dictionary values && + values.TryGetValue("a", out var a) && + values.TryGetValue("b", out var b)) + { + return Convert.ToDouble(a) + Convert.ToDouble(b); + } + + return double.NaN; + }); +} + +static void StartClock(BrowserWindow window) +{ + var timer = new Timer(_ => Electron.IpcMain.Send(window, "clock", DateTime.Now.ToString("T")), null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); + window.OnClosed += () => timer.Dispose(); +} diff --git a/src/ElectronNET.Samples.PreloadScript/Properties/electron-builder.json b/src/ElectronNET.Samples.PreloadScript/Properties/electron-builder.json new file mode 100644 index 00000000..41f483cc --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/Properties/electron-builder.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/refs/heads/master/packages/app-builder-lib/scheme.json", + "compression": "maximum", + "linux": { + "target": [ + "tar.xz" + ], + "executableArgs": [ "--no-sandbox" ], + "artifactName": "${name}-${arch}-${version}.${ext}" + }, + "win": { + "target": [ + { + "target": "portable", + "arch": "x64" + } + ] + } +} \ No newline at end of file diff --git a/src/ElectronNET.Samples.PreloadScript/Properties/launchSettings.json b/src/ElectronNET.Samples.PreloadScript/Properties/launchSettings.json new file mode 100644 index 00000000..6d8e62dd --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:0", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/ElectronNET.Samples.PreloadScript/README.md b/src/ElectronNET.Samples.PreloadScript/README.md new file mode 100644 index 00000000..42605e60 --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/README.md @@ -0,0 +1,42 @@ +# Electron.NET Sample: Preload Script + +This sample shows how to inject a [preload script](https://www.electronjs.org/docs/latest/tutorial/tutorial-preload) into a `BrowserWindow` and use it to set up IPC messaging between the web content and the .NET app — with Node.js integration **disabled** and context isolation **enabled**. + +## What it shows + +| Direction | Renderer side (via `window.dotnet`) | .NET side | +| --- | --- | --- | +| Page → .NET | `ipcRenderer.send("greet", name)` | `Electron.IpcMain.On("greet", ...)` | +| Page → .NET → Page | `ipcRenderer.invoke("get-runtime-info")` | `Electron.IpcMain.Handle("get-runtime-info", ...)` | +| .NET → Page | `ipcRenderer.on("clock", ...)` | `Electron.IpcMain.Send(window, "clock", ...)` | + +## How it works + +1. **`Preload/preload.js`** uses `contextBridge.exposeInMainWorld` to expose a small, purpose-built `window.dotnet` API. The page never sees `ipcRenderer` itself. +2. **The `.csproj`** copies the preload script to the output directory. Electron loads preload scripts from the file system, not via HTTP, so it must not (only) live in `wwwroot`. +3. **`Program.cs`** registers the IPC handlers, then creates the window with an absolute path to the script: + + ```csharp + WebPreferences = new WebPreferences + { + Preload = Path.Combine(AppContext.BaseDirectory, "Preload", "preload.js"), + NodeIntegration = false, + ContextIsolation = true, + Sandbox = true, + } + ``` + + `AppContext.BaseDirectory` resolves correctly both when debugging and in a packaged app (where the .NET app is placed in `resources/bin`). +4. **`wwwroot/app.js`** is a plain page script that only talks to `window.dotnet`. If the page is opened in a normal browser, it detects that the API is missing. + +> [!NOTE] +> Setting `NodeIntegration` explicitly matters: if `WebPreferences` do not specify it, Electron.NET enables Node.js integration and disables context isolation for backwards compatibility. + +> [!NOTE] +> With `Sandbox = true`, the preload script can only `require` a limited set of modules (such as `electron`'s `contextBridge` and `ipcRenderer`). Set it to `false` if your preload script needs full Node.js access. + +## Run + +```sh +dotnet run +``` diff --git a/src/ElectronNET.Samples.PreloadScript/wwwroot/app.css b/src/ElectronNET.Samples.PreloadScript/wwwroot/app.css new file mode 100644 index 00000000..1ffcec57 --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/wwwroot/app.css @@ -0,0 +1,47 @@ +:root { + color-scheme: light dark; + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +body { + max-width: 760px; + margin: 0 auto; + padding: 1.5rem; + line-height: 1.5; +} + +section { + margin-top: 1.5rem; + padding: 1rem; + border: 1px solid #8884; + border-radius: 8px; +} + +h2 { + margin-top: 0; + font-size: 1.1rem; +} + +input[type="number"] { + width: 5rem; +} + +pre { + background: #8881; + padding: 0.5rem; + border-radius: 4px; + min-height: 1rem; +} + +.status { + padding: 0.5rem 0.75rem; + border-radius: 4px; +} + +.status.ok { + background: #2e7d3233; +} + +.status.error { + background: #c6282833; +} diff --git a/src/ElectronNET.Samples.PreloadScript/wwwroot/app.js b/src/ElectronNET.Samples.PreloadScript/wwwroot/app.js new file mode 100644 index 00000000..3d3be259 --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/wwwroot/app.js @@ -0,0 +1,32 @@ +// Regular page script: it only knows about `window.dotnet`, which the preload script provides. +const $ = (id) => document.getElementById(id); +const api = window.dotnet; + +if (!api) { + $("status").textContent = + "window.dotnet is not available - the page is not running inside the Electron window with the preload script."; + $("status").classList.add("error"); +} else { + $("status").textContent = "Preload script is active: window.dotnet is available."; + $("status").classList.add("ok"); + + $("greet-form").addEventListener("submit", (e) => { + e.preventDefault(); + api.greet($("name").value); + }); + + api.onGreeting((text) => ($("greeting").textContent = text)); + + $("runtime-info").addEventListener("click", async () => { + const info = await api.getRuntimeInfo(); + $("runtime-info-result").textContent = JSON.stringify(info, null, 2); + }); + + $("add-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const sum = await api.add(Number($("a").value), Number($("b").value)); + $("sum").textContent = ` = ${sum}`; + }); + + api.onClock((time) => ($("clock").textContent = time)); +} diff --git a/src/ElectronNET.Samples.PreloadScript/wwwroot/index.html b/src/ElectronNET.Samples.PreloadScript/wwwroot/index.html new file mode 100644 index 00000000..410b2e69 --- /dev/null +++ b/src/ElectronNET.Samples.PreloadScript/wwwroot/index.html @@ -0,0 +1,50 @@ + + + + + + + Preload Script Sample + + + +

Preload Script Sample

+

+ The window was created with a preload script (Preload/preload.js) that exposes a small + window.dotnet API via contextBridge. Node.js integration is disabled and + the context is isolated. +

+ +

Checking for the preload script...

+ +
+

1. Page → .NET → Page (send / reply)

+
+ + +
+ +
+ +
+

2. Request / response (invoke / handle)

+ +

+
+        
+ + + + + + +
+
+ +
+

3. .NET → Page (push)

+

The .NET timer says it is …

+
+ + + + diff --git a/src/ElectronNET.sln b/src/ElectronNET.sln index c19b2cbd..8fcc32e3 100644 --- a/src/ElectronNET.sln +++ b/src/ElectronNET.sln @@ -76,6 +76,24 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElectronNET.Samples.Electro {8860606D-6847-F22A-5AED-DF4E0984DD24} = {8860606D-6847-F22A-5AED-DF4E0984DD24} EndProjectSection EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElectronNET.Samples.PreloadScript", "ElectronNET.Samples.PreloadScript\ElectronNET.Samples.PreloadScript.csproj", "{4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01}" + ProjectSection(ProjectDependencies) = postProject + {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} = {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} + {8860606D-6847-F22A-5AED-DF4E0984DD24} = {8860606D-6847-F22A-5AED-DF4E0984DD24} + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElectronNET.Samples.AppIcons", "ElectronNET.Samples.AppIcons\ElectronNET.Samples.AppIcons.csproj", "{6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12}" + ProjectSection(ProjectDependencies) = postProject + {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} = {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} + {8860606D-6847-F22A-5AED-DF4E0984DD24} = {8860606D-6847-F22A-5AED-DF4E0984DD24} + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElectronNET.Samples.BlazorServer", "ElectronNET.Samples.BlazorServer\ElectronNET.Samples.BlazorServer.csproj", "{8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23}" + ProjectSection(ProjectDependencies) = postProject + {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} = {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} + {8860606D-6847-F22A-5AED-DF4E0984DD24} = {8860606D-6847-F22A-5AED-DF4E0984DD24} + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -127,6 +145,18 @@ Global {B8D65F3A-7E54-4632-9F1C-46679237B312}.Debug|Any CPU.Build.0 = Debug|Any CPU {B8D65F3A-7E54-4632-9F1C-46679237B312}.Release|Any CPU.ActiveCfg = Release|Any CPU {B8D65F3A-7E54-4632-9F1C-46679237B312}.Release|Any CPU.Build.0 = Release|Any CPU + {4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01}.Release|Any CPU.Build.0 = Release|Any CPU + {6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12}.Release|Any CPU.Build.0 = Release|Any CPU + {8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -144,6 +174,9 @@ Global {AE877E48-6B44-63C2-8EA0-DB58D096B553} = {75129C45-FC6F-41B0-A485-07F4A7E031ED} {1C5FD66E-A1C6-C436-DF7C-3ECE4FEDDFE6} = {1BB6F634-2831-4496-83A6-BC6761DCEC8D} {B8D65F3A-7E54-4632-9F1C-46679237B312} = {EDCBFC49-2AEE-4BAF-9368-4409298C52FC} + {4E1C7B2A-9D3F-4A6B-8C5E-2F7A1B3D9E01} = {EDCBFC49-2AEE-4BAF-9368-4409298C52FC} + {6A2D8C4E-1B5F-4C7A-9E3D-5B8F2A6C0D12} = {EDCBFC49-2AEE-4BAF-9368-4409298C52FC} + {8C3E9D5F-2A6B-4D8C-AF4E-6C9A3B7D1E23} = {EDCBFC49-2AEE-4BAF-9368-4409298C52FC} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {81A62E71-9E04-4EFE-AD5C-23165375F8EF}