mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-09-21 22:45:20 +00:00
Update wiki 87cc6f98b6
@@ -9,6 +9,11 @@ See [System Requirements](System-Requirements).
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
> [!Tip]
|
||||
> To skip the manual setup below, scaffold a ready-to-run app with the
|
||||
> [project templates](Templates): `dotnet new install ElectronNET.Core.Templates` followed by
|
||||
> `dotnet new electron-blazor -n MyDesktopApp`.
|
||||
|
||||
### 1. Create ASP.NET Core Project
|
||||
|
||||
#### Visual Studio
|
||||
|
||||
@@ -27,9 +27,77 @@ These are the current default values when you don't make any changes:
|
||||
<ElectronPackageId>$(MSBuildProjectName.Replace(".", "-").ToLower())</ElectronPackageId>
|
||||
<ElectronBuilderJson>electron-builder.json</ElectronBuilderJson>
|
||||
<Title>$(MSBuildProjectName)</Title>
|
||||
<ElectronExecutableName></ElectronExecutableName>
|
||||
<ElectronRootDir>../..</ElectronRootDir>
|
||||
<ElectronSkipExecCommands>false</ElectronSkipExecCommands>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
### Product Name and Executable Name
|
||||
|
||||
`Title` is the product name of the application. It is used for the window title, the installer, the macOS app bundle and the Linux desktop entry, and it may contain spaces and other characters that are awkward in a file name.
|
||||
|
||||
`ElectronExecutableName` controls the name of the executable inside the package (electron-builder's `executableName`). When it is not set, it defaults to the following behavior:
|
||||
|
||||
| Target | Default |
|
||||
| --- | --- |
|
||||
| Windows | `$(Title)` |
|
||||
| Linux / macOS | `$(ElectronPackageId)` |
|
||||
|
||||
So to ship a product called `My Great App` with a `mygreatapp` binary on every platform:
|
||||
|
||||
```xml
|
||||
<PropertyGroup>
|
||||
<Title>My Great App</Title>
|
||||
<ElectronExecutableName>mygreatapp</ElectronExecutableName>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `ElectronExecutable` is a separate, advanced setting: it is the binary Electron.NET launches when the .NET app starts first. It defaults to `ElectronExecutableName` and only needs to be changed when the package contains a launcher stub (for example added by an electron-builder hook) that should be started instead of the Electron binary.
|
||||
|
||||
### Custom Packaging Layout
|
||||
|
||||
`ElectronRootDir` tells the .NET app where to find the Electron binary when it is started first (DotNet-First startup of a packaged app). The path is resolved relative to the directory of the .NET executable; absolute paths are used as-is.
|
||||
|
||||
The default `../..` matches the standard Electron-First packaging layout produced by `dotnet publish`, where the .NET app is placed in `resources/bin` of the Electron package:
|
||||
|
||||
```
|
||||
<install-root>/
|
||||
MyApp # Electron executable
|
||||
resources/
|
||||
bin/
|
||||
MyApp # .NET executable
|
||||
```
|
||||
|
||||
If your own packaging pipeline places the .NET executable at the package root and Electron in a subdirectory, set `ElectronRootDir` accordingly:
|
||||
|
||||
```xml
|
||||
<ElectronRootDir>electron</ElectronRootDir>
|
||||
```
|
||||
|
||||
```
|
||||
<install-root>/
|
||||
MyApp # .NET executable
|
||||
electron/
|
||||
MyApp # Electron executable
|
||||
resources/
|
||||
locales/
|
||||
```
|
||||
|
||||
The property is also used to detect whether the app runs packaged or unpackaged, so it must point to the directory that actually contains the Electron binary.
|
||||
|
||||
### Build Extensibility
|
||||
|
||||
These properties are useful when Electron.NET is embedded into a custom build or CI pipeline:
|
||||
|
||||
| Property | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `ElectronSkipExecCommands` | `false` | Skips all `npm`/`npx` invocations of the Electron build and publish targets. Use it when the dependencies and the Electron distribution are provided by the pipeline itself (for example from a cache or an offline mirror). |
|
||||
| `ElectronIntermediatePublishDir` | `$(IntermediateOutputPath)PubTmp\` | Overrides the intermediate directory the .NET app is published to before it is assembled into the Electron package. |
|
||||
|
||||
`ElectronPackageId` and `Title` only fall back to the project name when they are not already set, so both can be defined by a `Directory.Build.props` or passed on the command line.
|
||||
|
||||
### Relation to package.json
|
||||
|
||||
ElectronNET.Core does not work with an `electron-manifest.json` file anymore.
|
||||
@@ -41,11 +109,17 @@ Since electron builder still expects a `package.json` file to exist, ElectronNET
|
||||
"productName": "$(ElectronTitle)",
|
||||
"build": {
|
||||
"appId": "$(ElectronPackageId)",
|
||||
"win": {
|
||||
"executableName": "$(ElectronExecutableName)"
|
||||
},
|
||||
"mac": {
|
||||
"executableName": "$(ElectronExecutableName)"
|
||||
},
|
||||
"linux": {
|
||||
"desktop": {
|
||||
"entry": { "Name": "$(Title)" }
|
||||
},
|
||||
"executableName": "$(ElectronPackageId)"
|
||||
"executableName": "$(ElectronExecutableName)"
|
||||
},
|
||||
"deb": {
|
||||
"desktop": {
|
||||
|
||||
@@ -53,7 +53,7 @@ Add the Electron.NET configuration to your `.csproj` file:
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="0.5.2" />
|
||||
<PackageReference Include="ElectronNET.Core" Version="0.6.0" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ This guide explains how to include and use a `custom_main.js` file in your Elect
|
||||
- Register custom protocol handlers (e.g., `myapp://`) — protocols must be registered before the app is fully initialized
|
||||
- Integrate Node.js modules (e.g., telemetry, OS APIs)
|
||||
- Control startup logic (abort, environment checks)
|
||||
- Modify Chromium / Electron.NET command line switches before they are evaluated
|
||||
- Set up IPC messaging or preload scripts
|
||||
|
||||
## Step-by-Step Process
|
||||
@@ -64,10 +65,29 @@ Use environment variables to control features:
|
||||
if (env === 'Development') { /* enable dev features */ }
|
||||
```
|
||||
|
||||
### Modifying Command Line Switches
|
||||
|
||||
`onStartup` is invoked before Electron.NET reads any of its own switches (`manifest`, `unpackedelectron`, `unpackeddotnet`, `dotnetpacked`, `electronforcedport`, `electronurl`), so the hook can append or override them:
|
||||
|
||||
```javascript
|
||||
module.exports.onStartup = function (host) {
|
||||
const { app } = require('electron');
|
||||
|
||||
// Force a fixed socket bridge port
|
||||
app.commandLine.appendSwitch('electronforcedport', '8000');
|
||||
|
||||
// Chromium switches, e.g. to disable the GPU sandbox
|
||||
app.commandLine.appendSwitch('disable-gpu-sandbox');
|
||||
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- `custom_main.js` must use CommonJS syntax (`module.exports.onStartup = ...`).
|
||||
- Place the file in your source directory and copy it to `.electron` using `.csproj`.
|
||||
- Electron.NET will abort startup if `onStartup` returns `false`.
|
||||
- `onStartup` runs before the Electron.NET command line switches are evaluated, so switches set there are picked up by the host.
|
||||
|
||||
### Complete example is available here [ElectronNetSampleApp](https://github.com/niteshsinghal85/ElectronNetSampleApp)
|
||||
@@ -16,6 +16,10 @@ When you build an Electron.NET project, the following validation checks are perf
|
||||
| [ELECTRON005](#4-parent-paths-not-allowed-in-electron-builderjson) | Parent paths not allowed | Checks for `..` references in config |
|
||||
| [ELECTRON006](#5-publish-profile-validation) | ASP.NET publish profile mismatch | Warns when ASP.NET projects have console-style profiles |
|
||||
| [ELECTRON007](#5-publish-profile-validation) | Console publish profile mismatch | Warns when console projects have ASP.NET-style profiles |
|
||||
| [ELECTRON010](#6-electronhosthook-folder-validation) | ElectronHostHook without package.json | Warns when hook TypeScript files exist without a `package.json` |
|
||||
| [ELECTRON011](#6-electronhosthook-folder-validation) | ElectronHostHook without tsconfig.json | Warns when hook TypeScript files exist without a `tsconfig.json` |
|
||||
|
||||
All checks skip the build output folders (`bin`, `obj`, `publish`, `.electron`, `node_modules`) as well as any custom output paths configured via `BaseOutputPath` / `BaseIntermediateOutputPath` (for example the .NET `artifacts` output layout).
|
||||
|
||||
---
|
||||
|
||||
@@ -31,7 +35,7 @@ Rules:
|
||||
|
||||
- **ELECTRON001**: `package.json` / `package-lock.json` must not exist in the project directory or subdirectories
|
||||
- Exception: `ElectronHostHook` folder is allowed
|
||||
- Note: a **root** `package.json` is **excluded** from `ELECTRON001` and validated by `ELECTRON008` / `ELECTRON009`
|
||||
- Note: a **root** `package.json` (and its `package-lock.json`) is **excluded** from `ELECTRON001` and validated by `ELECTRON008` / `ELECTRON009`
|
||||
|
||||
- **ELECTRON008**: If a root `package.json` exists, it must **not** contain electron-related dependencies or configuration.
|
||||
|
||||
@@ -112,6 +116,10 @@ The `electron.manifest.json` file format is deprecated. All configuration should
|
||||
"mac": {
|
||||
"icon": "Assets/app.icns",
|
||||
"target": ["dmg", "zip"]
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": true,
|
||||
"perMachine": false
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -207,7 +215,7 @@ The build system examines `.pubxml` files in the `Properties/PublishProfiles` fo
|
||||
|
||||
- **ELECTRON006**: For **ASP.NET projects** (using `Microsoft.NET.Sdk.Web`), checks that publish profiles include `WebPublishMethod`. This property is required for proper ASP.NET publishing.
|
||||
|
||||
- **ELECTRON007**: For **console/other projects** (not using the Web SDK), checks that publish profiles do NOT include the `WebPublishMethod` property. These ASP.NET-specific properties are incorrect for non-web applications.
|
||||
- **ELECTRON007**: For **console/other projects** (not using the Web SDK), checks that publish profiles do NOT include the `WebPublishMethod` or `ProjectGuid` property. These ASP.NET-specific properties are incorrect for non-web applications.
|
||||
|
||||
### Why this matters
|
||||
|
||||
@@ -232,9 +240,54 @@ For correct publish profile examples for both ASP.NET and Console applications,
|
||||
|
||||
---
|
||||
|
||||
## 6. ElectronHostHook Folder Validation
|
||||
|
||||
**Warning Codes:** `ELECTRON010`, `ELECTRON011`
|
||||
|
||||
### What is checked
|
||||
|
||||
If the project contains an `ElectronHostHook` folder with TypeScript files:
|
||||
|
||||
- **ELECTRON010**: The folder must contain a `package.json`
|
||||
- **ELECTRON011**: The folder must contain a `tsconfig.json`
|
||||
|
||||
### Why this matters
|
||||
|
||||
Custom host hook code is only compiled and packaged when the `ElectronHostHook` folder declares its npm dependencies in a `package.json`. If that file is missing, the hook is silently dropped and the corresponding `Electron.HostHook` calls fail at runtime. The `tsconfig.json` is required so the hook sources are compiled with the expected settings.
|
||||
|
||||
### How to fix
|
||||
|
||||
Add the missing files to the `ElectronHostHook` folder:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "electron-host-hook",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"socket.io": "^4.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **See also:** [HostHook API](HostHook)
|
||||
|
||||
---
|
||||
|
||||
## Disabling Migration Checks
|
||||
|
||||
If you need to disable specific migration checks (not recommended), you can set the following properties in your `.csproj` file:
|
||||
Individual checks can be downgraded to messages by their warning code:
|
||||
|
||||
```xml
|
||||
<PropertyGroup>
|
||||
<MSBuildWarningsAsMessages>$(MSBuildWarningsAsMessages);ELECTRON005</MSBuildWarningsAsMessages>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
If you need to disable all migration checks (not recommended), you can set the following property in your `.csproj` file:
|
||||
|
||||
```xml
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -47,17 +47,19 @@ You can also manually edit `electron-builder.json`:
|
||||
```json
|
||||
{
|
||||
"linux": {
|
||||
"target": [
|
||||
"tar.xz"
|
||||
]
|
||||
"target": ["tar.xz"]
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
{
|
||||
"target": "portable",
|
||||
"target": "nsis",
|
||||
"arch": "x64"
|
||||
}
|
||||
]
|
||||
},
|
||||
"nsis": {
|
||||
"oneClick": true,
|
||||
"perMachine": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -221,6 +221,15 @@ The publish process will:
|
||||
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
|
||||
|
||||
|
||||
## Custom Packaging Pipelines
|
||||
|
||||
The default layout is Electron-First: electron-builder produces the Electron package and the .NET app is placed in `resources/bin`. If you assemble the package yourself and put the .NET executable at the package root with Electron in a subdirectory, set `ElectronRootDir` so the .NET app can locate the Electron binary at runtime.
|
||||
|
||||
For pipelines that provide the npm dependencies themselves, `ElectronSkipExecCommands` suppresses all `npm`/`npx` invocations, and `ElectronIntermediatePublishDir` redirects the intermediate publish output.
|
||||
|
||||
See [Configuration](Configuration#custom-packaging-layout) for details.
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Startup Methods](Startup-Methods)** - Understanding different launch modes for packaged apps
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
# 0.6.0
|
||||
|
||||
## ElectronNET.Core
|
||||
|
||||
- Updated dependencies
|
||||
- Updated `WebContents` zoom level APIs to use `double` instead of `int` (#956)
|
||||
- Improved migration checks to honor custom output paths and to detect `ProjectGuid` in publish profiles (#946)
|
||||
- Fixed single instance handling on macOS (#1040)
|
||||
- Fixed slow socket bridge startup by binding to an explicit loopback address (#1103)
|
||||
- Fixed socket bridge connection when a system proxy is configured (#1105)
|
||||
- Fixed electron-builder using the host RID instead of the target RID (#1097)
|
||||
- Fixed cross-compilation behavior on same platform (#1098) @epsnm
|
||||
- Fixed resolution of unrelated target (#1099) @epsnm
|
||||
- Fixed false alarm for `ELECTRON001` on a root `package-lock.json` (#946)
|
||||
- Added `ElectronNET.Core.Templates` package with a `dotnet new electron-blazor` template (#414)
|
||||
- Added `WebContents.OnZoomChanged` event (#956)
|
||||
- Added `WebContents` page loading APIs `LoadFileAsync`, `IsLoadingAsync`, `IsLoadingMainFrameAsync`, `IsWaitingForResponseAsync`, `Reload`, `ReloadIgnoringCache` and `Stop` (#956)
|
||||
- Added `WebContents.InsertCSSAsync` and `WebContents.RemoveInsertedCSSAsync` for dynamic CSS (#956)
|
||||
- Added `WebContents` editing and selection APIs (undo, redo, cut, copy, paste, insert text, select, ...) (#956)
|
||||
- Added `WebContents.FindInPageAsync`, `WebContents.StopFindInPage` and the `OnFoundInPage` event (#956)
|
||||
- Added `WebContents` audio events `OnAudioStateChanged`, `OnMediaStartedPlaying` and `OnMediaPaused` (#956)
|
||||
- Added `WebContents.ScrollToTop` and `WebContents.ScrollToBottom` (#956)
|
||||
- Added target framework customization (#1095) @epsnm
|
||||
- Added configurable Electron root directory for custom packaging layouts (#1106) @DYH1319
|
||||
- Added ability for `custom_main.js` to modify command line switches (#1029) @AeonSake
|
||||
- Added migration checks for incomplete `ElectronHostHook` folders (`ELECTRON010`, `ELECTRON011`) (#946)
|
||||
- Added `ElectronExecutableName` to separate the product name from the executable name (#1003) @AeonSake
|
||||
- Added build extensibility properties `ElectronSkipExecCommands` and `ElectronIntermediatePublishDir` (#1106) @DYH1319
|
||||
|
||||
# 0.5.2
|
||||
|
||||
## ElectronNET.Core
|
||||
|
||||
87
Templates.md
Normal file
87
Templates.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Project Templates
|
||||
|
||||
Electron.NET ships a `dotnet new` template package so you can scaffold a ready-to-run desktop app instead of wiring up an ASP.NET project by hand.
|
||||
|
||||
## 🛠 System Requirements
|
||||
|
||||
See [System Requirements](System-Requirements).
|
||||
|
||||
## 📦 Install the Templates
|
||||
|
||||
```bash
|
||||
dotnet new install ElectronNET.Core.Templates
|
||||
```
|
||||
|
||||
To update to the latest version, run the same command again. To remove them:
|
||||
|
||||
```bash
|
||||
dotnet new uninstall ElectronNET.Core.Templates
|
||||
```
|
||||
|
||||
## 🚀 Available Templates
|
||||
|
||||
| Template | Short name | Description |
|
||||
|----------|------------|-------------|
|
||||
| Electron.NET Blazor App | `electron-blazor` | A Blazor Server app hosted in an Electron shell |
|
||||
|
||||
## 🧱 Create a Blazor App
|
||||
|
||||
```bash
|
||||
dotnet new electron-blazor -n MyDesktopApp
|
||||
cd MyDesktopApp
|
||||
```
|
||||
|
||||
Then start it in the Electron shell:
|
||||
|
||||
```bash
|
||||
dotnet build
|
||||
dotnet run
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
| Option | Values | Default | Description |
|
||||
|--------|--------|---------|-------------|
|
||||
| `-f`, `--framework` | `net8.0`, `net10.0` | `net10.0` | The target framework of the generated project |
|
||||
| `-e`, `--electron-version` | any Electron version | `38.2.2` | The Electron version the app is built against |
|
||||
| `-p`, `--port` | port number | `8001` | The port the ASP.NET server uses during development |
|
||||
| `--no-restore` | — | — | Skip the automatic `dotnet restore` |
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
dotnet new electron-blazor -n MyDesktopApp -f net10.0 -e 30.4.0 -p 8123
|
||||
```
|
||||
|
||||
## 📁 What You Get
|
||||
|
||||
```
|
||||
MyDesktopApp/
|
||||
├── Components/
|
||||
│ ├── Layout/ MainLayout.razor, NavMenu.razor
|
||||
│ ├── Pages/ Home.razor, Counter.razor
|
||||
│ ├── App.razor
|
||||
│ ├── Routes.razor
|
||||
│ └── _Imports.razor
|
||||
├── Properties/
|
||||
│ ├── PublishProfiles/ win-x64, linux-x64 and osx-arm64 folder profiles
|
||||
│ ├── electron-builder.json
|
||||
│ └── launchSettings.json
|
||||
├── wwwroot/app.css
|
||||
├── appsettings.json
|
||||
├── Program.cs
|
||||
└── MyDesktopApp.csproj
|
||||
```
|
||||
|
||||
The project already references `ElectronNET.Core` and `ElectronNET.Core.AspNet`, calls `builder.UseElectron(...)` in `Program.cs`, and passes all [Migration Checks](Migration-Checks) out of the box.
|
||||
|
||||
> [!Note]
|
||||
> `ElectronNET.API` also defines a type named `App`, which collides with the Blazor root
|
||||
> component. That is why the template calls `app.MapRazorComponents<MyDesktopApp.Components.App>()`
|
||||
> with a fully qualified type name.
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Configuration](Configuration)** - Adjust app metadata and Electron settings
|
||||
- **[Debugging](Debugging)** - Debug the .NET and Electron sides
|
||||
- **[Package Building](Package-Building)** - Create distributable packages
|
||||
208
WebContents.md
208
WebContents.md
@@ -57,6 +57,23 @@ Works for both BrowserWindows and BrowserViews.
|
||||
- `isBrowserWindow` - Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)
|
||||
- `path` - Absolute path to the CSS file location
|
||||
|
||||
#### 🧊 `Task<string> InsertCSSAsync(string css, string cssOrigin = null)`
|
||||
Injects CSS into the current web page and returns a unique key for the inserted style sheet.
|
||||
|
||||
**Parameters:**
|
||||
- `css` - The style sheet to inject
|
||||
- `cssOrigin` - Can be either `user` or `author`, defaults to `author`
|
||||
|
||||
**Returns:**
|
||||
|
||||
The key of the inserted style sheet, to be used with `RemoveInsertedCSSAsync`.
|
||||
|
||||
#### 🧊 `Task RemoveInsertedCSSAsync(string key)`
|
||||
Removes a previously inserted style sheet from the current web page.
|
||||
|
||||
**Parameters:**
|
||||
- `key` - The key returned by `InsertCSSAsync`
|
||||
|
||||
#### 🧊 `Task LoadURLAsync(string url)`
|
||||
Loads the url in the window. The url must contain the protocol prefix.
|
||||
|
||||
@@ -112,6 +129,106 @@ Prints window's web page as PDF with Chromium's preview printing custom settings
|
||||
|
||||
Whether the PDF generation succeeded.
|
||||
|
||||
#### 🧊 `Task<double> GetZoomFactorAsync()`
|
||||
Returns the current zoom factor. A factor of `1.0` means 100%.
|
||||
|
||||
#### 🧊 `void SetZoomFactor(double factor)`
|
||||
Changes the zoom factor to the specified factor. The zoom factor is the zoom percent divided by 100, so 300% = `3.0`. The factor must be greater than `0.0`.
|
||||
|
||||
**Parameters:**
|
||||
- `factor` - The zoom factor
|
||||
|
||||
#### 🧊 `Task<double> GetZoomLevelAsync()`
|
||||
Returns the current zoom level.
|
||||
|
||||
#### 🧊 `void SetZoomLevel(double level)`
|
||||
Changes the zoom level to the specified level. The original size is `0` and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of the original size, respectively.
|
||||
|
||||
**Parameters:**
|
||||
- `level` - The zoom level
|
||||
|
||||
#### 🧊 `Task SetVisualZoomLevelLimitsAsync(double minimumLevel, double maximumLevel)`
|
||||
Sets the maximum and minimum pinch-to-zoom level.
|
||||
|
||||
**Parameters:**
|
||||
- `minimumLevel` - The minimum pinch-to-zoom level
|
||||
- `maximumLevel` - The maximum pinch-to-zoom level
|
||||
|
||||
#### 🧊 `Task LoadFileAsync(string filePath, LoadFileOptions options = null)`
|
||||
Loads the given HTML file, relative to the root of the application.
|
||||
|
||||
**Parameters:**
|
||||
- `filePath` - Path to the HTML file
|
||||
- `options` - Optional `Query`, `Search` and `Hash` parts of the resulting URL
|
||||
|
||||
#### 🧊 `void SetAudioMuted(bool muted)`
|
||||
Mutes or unmutes the audio on the current web page.
|
||||
|
||||
#### 🧊 `Task<bool> IsAudioMutedAsync()`
|
||||
Whether this page has been muted.
|
||||
|
||||
#### 🧊 `Task<bool> IsCurrentlyAudibleAsync()`
|
||||
Whether audio is currently playing.
|
||||
|
||||
#### 🧊 `Task<string> GetUserAgentAsync()` / `void SetUserAgent(string userAgent)`
|
||||
Gets or overrides the user agent for this web page.
|
||||
|
||||
#### 🧊 `Task<bool> IsLoadingAsync()`
|
||||
Whether the web page is still loading resources.
|
||||
|
||||
#### 🧊 `Task<bool> IsLoadingMainFrameAsync()`
|
||||
Whether the main frame (and not just iframes or frames within it) is still loading.
|
||||
|
||||
#### 🧊 `Task<bool> IsWaitingForResponseAsync()`
|
||||
Whether the web page is waiting for a first response from the main resource of the page.
|
||||
|
||||
#### 🧊 `void Reload()`
|
||||
Reloads the current web page.
|
||||
|
||||
#### 🧊 `void ReloadIgnoringCache()`
|
||||
Reloads the current web page and ignores the cache.
|
||||
|
||||
#### 🧊 `void Stop()`
|
||||
Stops any pending navigation.
|
||||
|
||||
#### 🧊 `void Undo()` / `void Redo()`
|
||||
Executes the `undo` / `redo` editing command in the web page.
|
||||
|
||||
#### 🧊 `void Cut()` / `void Copy()` / `void Paste()` / `void PasteAndMatchStyle()` / `void Delete()`
|
||||
Executes the corresponding editing command in the web page.
|
||||
|
||||
#### 🧊 `void CopyImageAt(int x, int y)`
|
||||
Copies the image at the given position to the clipboard.
|
||||
|
||||
#### 🧊 `void SelectAll()` / `void Unselect()` / `void CenterSelection()`
|
||||
Selects all content, clears the selection, or scrolls to the current selection.
|
||||
|
||||
#### 🧊 `void ScrollToTop()` / `void ScrollToBottom()`
|
||||
Scrolls to the top or the bottom of the current web page.
|
||||
|
||||
#### 🧊 `void AdjustSelection(AdjustSelectionOptions options)`
|
||||
Adjusts the start and end points of the current text selection by the given amounts. Negative amounts move towards the beginning of the document.
|
||||
|
||||
#### 🧊 `Task InsertTextAsync(string text)`
|
||||
Inserts text into the focused element.
|
||||
|
||||
#### 🧊 `void Replace(string text)` / `void ReplaceMisspelling(string text)`
|
||||
Replaces the current selection, or the currently misspelled word, with the given text.
|
||||
|
||||
#### 🧊 `Task<int> FindInPageAsync(string text, FindInPageOptions options = null)`
|
||||
Starts a request to find all matches for the text in the web page. Results are reported via the `OnFoundInPage` event.
|
||||
|
||||
**Parameters:**
|
||||
- `text` - Content to be searched, must not be empty
|
||||
- `options` - Optional `Forward`, `FindNext` and `MatchCase` flags
|
||||
|
||||
**Returns:**
|
||||
|
||||
The request id of the find request.
|
||||
|
||||
#### 🧊 `void StopFindInPage(StopFindInPageAction action)`
|
||||
Stops any `FindInPageAsync` request with the given action (`ClearSelection`, `KeepSelection` or `ActivateSelection`).
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `InputEvent`
|
||||
@@ -141,6 +258,21 @@ Emitted when the document in the top-level frame is loaded.
|
||||
#### ⚡ `OnWillRedirect`
|
||||
Emitted when a server side redirect occurs during navigation.
|
||||
|
||||
#### ⚡ `OnZoomChanged`
|
||||
Emitted when the user changes the zoom level using the mouse wheel or the keyboard. The handler receives the `ZoomDirection` (`In` or `Out`).
|
||||
|
||||
#### ⚡ `OnFoundInPage`
|
||||
Emitted when a result is available for a `FindInPageAsync` request. The handler receives a `FoundInPageResult`.
|
||||
|
||||
#### ⚡ `OnAudioStateChanged`
|
||||
Emitted when media becomes audible or inaudible. The handler receives `true` if one or more frames or child web contents are emitting audio.
|
||||
|
||||
#### ⚡ `OnMediaStartedPlaying`
|
||||
Emitted when media starts playing.
|
||||
|
||||
#### ⚡ `OnMediaPaused`
|
||||
Emitted when media is paused or done playing.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Page Loading
|
||||
@@ -278,6 +410,82 @@ webContents.OnCrashed += (killed) =>
|
||||
};
|
||||
```
|
||||
|
||||
### Zoom Control
|
||||
|
||||
```csharp
|
||||
// Set the zoom to 150%
|
||||
webContents.SetZoomFactor(1.5);
|
||||
|
||||
var factor = await webContents.GetZoomFactorAsync();
|
||||
Console.WriteLine($"Current zoom: {factor * 100}%");
|
||||
|
||||
// Zoom levels are relative: each step is 20% larger/smaller, 0 is the original size
|
||||
webContents.SetZoomLevel(2);
|
||||
|
||||
// Restrict pinch-to-zoom
|
||||
await webContents.SetVisualZoomLevelLimitsAsync(1, 3);
|
||||
|
||||
// React to zoom changes triggered by the user
|
||||
webContents.OnZoomChanged += (direction) =>
|
||||
{
|
||||
Console.WriteLine($"User zoomed {direction}");
|
||||
};
|
||||
```
|
||||
|
||||
> **Note:** The zoom factor is shared by all windows using the same session partition. Assign a unique `WebPreferences.Partition` per window if each window should keep its own zoom.
|
||||
|
||||
### Dynamic CSS
|
||||
|
||||
```csharp
|
||||
var key = await webContents.InsertCSSAsync("body { background-color: #202020; }");
|
||||
|
||||
// ... later
|
||||
await webContents.RemoveInsertedCSSAsync(key);
|
||||
```
|
||||
|
||||
### Editing and Selection
|
||||
|
||||
```csharp
|
||||
await webContents.InsertTextAsync("Hello from .NET");
|
||||
|
||||
webContents.SelectAll();
|
||||
webContents.Copy();
|
||||
webContents.Unselect();
|
||||
```
|
||||
|
||||
### Find in Page
|
||||
|
||||
```csharp
|
||||
webContents.OnFoundInPage += (result) =>
|
||||
{
|
||||
Console.WriteLine($"{result.ActiveMatchOrdinal}/{result.Matches} matches");
|
||||
|
||||
if (result.FinalUpdate)
|
||||
{
|
||||
webContents.StopFindInPage(StopFindInPageAction.ClearSelection);
|
||||
}
|
||||
};
|
||||
|
||||
var requestId = await webContents.FindInPageAsync("electron", new FindInPageOptions { MatchCase = false });
|
||||
```
|
||||
|
||||
### Audio
|
||||
|
||||
```csharp
|
||||
webContents.SetAudioMuted(true);
|
||||
|
||||
var muted = await webContents.IsAudioMutedAsync();
|
||||
var audible = await webContents.IsCurrentlyAudibleAsync();
|
||||
|
||||
webContents.OnAudioStateChanged += (isAudible) =>
|
||||
{
|
||||
Console.WriteLine(isAudible ? "Page started emitting audio" : "Page went silent");
|
||||
};
|
||||
|
||||
webContents.OnMediaStartedPlaying += () => Console.WriteLine("Media playing");
|
||||
webContents.OnMediaPaused += () => Console.WriteLine("Media paused");
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager) - Windows containing web contents
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
<img src="wiki/Getting-Started.svg" width="80%" valign="middle" />
|
||||
|
||||
- [System Requirements](System-Requirements)<img src="wiki/trans.png" width="2" height="22" valign="bottom">
|
||||
- [Project Templates](Templates)<img src="wiki/trans.png" width="2" height="22" valign="bottom">
|
||||
- [With ASP.Net](ASP.Net)<img src="wiki/trans.png" width="2" height="22" valign="bottom">
|
||||
- [With a Console App](Console-App)<img src="wiki/trans.png" width="2" height="22" valign="bottom">
|
||||
|
||||
|
||||
Reference in New Issue
Block a user