基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-03 2fd6e68025d4b987cfde52b8402038ca34116876
src/Moli.Desktop/WebView/WebViewHost.cs
@@ -2,6 +2,7 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Windows;
using System.Drawing;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using Moli.Desktop.Diagnostics;
@@ -23,6 +24,7 @@
    };
    private PluginBridgeContext? _bridgeContext;
    private WebViewHostOptions? _options;
    private IDisposable? _audioSubscription;
    private bool _initialized;
    public WebViewHost(
@@ -51,10 +53,20 @@
        Directory.CreateDirectory(options.UserDataFolder);
        var environment = await CoreWebView2Environment.CreateAsync(null, options.UserDataFolder).ConfigureAwait(true);
        await Control.EnsureCoreWebView2Async(environment).ConfigureAwait(true);
        if (options.IsTransparent)
        {
            Control.DefaultBackgroundColor = Color.Transparent;
        }
        Control.CoreWebView2.Settings.AreDevToolsEnabled = options.AreDevToolsEnabled;
        Control.CoreWebView2.IsMuted = options.IsMuted;
        Control.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
        Control.CoreWebView2.ScreenCaptureStarting += OnScreenCaptureStarting;
        Control.NavigationCompleted += OnNavigationCompleted;
        if (HasPermission("audio-capture"))
        {
            _audioSubscription = _events.Subscribe(DispatchAudioSpectrumAsync);
        }
        if (!string.IsNullOrWhiteSpace(options.InitialScript))
        {
@@ -113,14 +125,36 @@
    public async ValueTask DisposeAsync()
    {
        _audioSubscription?.Dispose();
        _audioSubscription = null;
        if (Control.CoreWebView2 is not null)
        {
            Control.CoreWebView2.WebMessageReceived -= OnWebMessageReceived;
            Control.CoreWebView2.ScreenCaptureStarting -= OnScreenCaptureStarting;
        }
        Control.NavigationCompleted -= OnNavigationCompleted;
        Control.Dispose();
        await Task.CompletedTask;
    }
    private Task DispatchAudioSpectrumAsync(RuntimeEvent runtimeEvent)
    {
        if (runtimeEvent.Name != "audio.spectrum" || runtimeEvent.Payload is null)
        {
            return Task.CompletedTask;
        }
        var detail = JsonSerializer.Serialize(runtimeEvent.Payload, _jsonOptions);
        var script = $"window.dispatchEvent(new CustomEvent(\"moli:audio-spectrum\", {{ detail: {detail} }}));";
        var dispatcher = Control.Dispatcher;
        if (dispatcher.CheckAccess())
        {
            return ExecuteScriptSafelyAsync(script);
        }
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
    private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
@@ -165,6 +199,36 @@
        }).ConfigureAwait(false);
    }
    private void OnScreenCaptureStarting(object? sender, CoreWebView2ScreenCaptureStartingEventArgs e)
    {
        e.Cancel = true;
        e.Handled = true;
        _diagnostics.Record(
            DiagnosticSeverity.Info,
            "WebViewScreenCaptureBlocked",
            "WebView screen capture request was blocked.",
            new Dictionary<string, string> { ["hostId"] = HostId, ["pluginId"] = PluginId.Value });
    }
    private async Task ExecuteScriptSafelyAsync(string script)
    {
        if (!_initialized || Control.CoreWebView2 is null)
        {
            return;
        }
        try
        {
            await Control.ExecuteScriptAsync(script).ConfigureAwait(true);
        }
        catch (InvalidOperationException)
        {
        }
    }
    private bool HasPermission(string permission)
        => _plugin.Manifest.Permissions.Any(item => string.Equals(item, permission, StringComparison.OrdinalIgnoreCase));
    private void EnsureInitialized()
    {
        if (!_initialized || Control.CoreWebView2 is null || _options is null)