页面加载
2025/3/12原创大约 2 分钟约 459 字
1. 添加组件
在 WPF 项目中通过 NuGet 添加 Microsoft.Web.WebView2
包
2. xaml 部署文件
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<wv2:WebView2 x:Name="webView" />
</Grid>
</Window>
3. cs 实现方法
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.WebView2.Core;
namespace WpfApp1;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
load();
}
private async void load()
{
//初始化 WebView2 内核
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"vue.app",
"D:\\我的资料库\\Documents\\Downloads\\vue-demo\\dist",
CoreWebView2HostResourceAccessKind.Allow
);
webView.CoreWebView2.Navigate("http://localhost:8080/");
//直接调用web地址
// webView.Source = new Uri("https://your-page.com");
//Thread.Sleep(5000);
//await webView.EnsureCoreWebView2Async();
//MessageBox.Show("vueFunction");
//监听页面加载完成事件
webView.NavigationCompleted += async (sender, e) =>
{
await webView.CoreWebView2.ExecuteScriptAsync("window.vueFunction()");
string param1 = "Hello";
string param2 = "World";
string script = $"window.vueMethodWithParams('{param1}', '{param2}')";
//MessageBox.Show(script);
string res = await webView.CoreWebView2.ExecuteScriptAsync(script);
//MessageBox.Show(res);
};
}
}
4. 异步调用 js
// 安装 NuGet 包:WebView2.DevTools.Dom
await using var devToolsContext = await webView.CoreWebView2.CreateDevToolsContextAsync();
string jsCode = @"() => new Promise(resolve => {
setTimeout(() => resolve('Async Result'), 2000);
})";
// 等待 Promise 完成(设置超时)
string result = await devToolsContext.EvaluateFunctionAsync<string>(jsCode)
.WaitAsync(TimeSpan.FromSeconds(10)); // 输出 "Async Result":ml-citation{ref="5" data="citationList"}
5. vue 实现方法
<template>
<div>
<h1>Vue App</h1>
<button @click="vueMethod">Vue Method</button>
<button @click="vueMethodWithParams">Vue Method with Params</button>
</div>
</template>
<script>
export default {
methods: {
//无参方法
vueMethod() {
alert('Vue Method Called');
},
//有参数的情况
vueMethodWithParams(param1, param2) {
alert(`Vue Method with Params Called: ${param1}, ${param2}`);
}
}
}
</script>
6. 双向通信机制
6.1. C#调用JS
参考上述 ExecuteScriptAsync 或 EvaluateFunctionAsync 方法。
6.1.1. JS调用C
注册宿主对象
public class JSBridge {
public void CloseWindow() => Application.Current.Shutdown();
}
var bridge = new JSBridge();
webView.CoreWebView2.AddHostObjectToScript("bridge", bridge); // 对象名需唯一:ml-citation{ref="3,6" data="citationList"}
调用方法
// 异步调用(需 await)
async function callCSharpMethod() {
await window.chrome.webview.hostObjects.bridge.CloseWindow();
}