前后段支持互发消息并支持调试

This commit is contained in:
ShaoHua
2026-03-11 21:54:04 +08:00
parent dc23416d7e
commit be9b042a05
16 changed files with 1480 additions and 5 deletions
+16
View File
@@ -0,0 +1,16 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "msedge",
"request": "launch",
"name": "Launch Edge against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}
+9 -4
View File
@@ -1,4 +1,4 @@
<Window x:Class="WebView2Demo.MainWindow"
<Window x:Class="WebView2Demo.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"
@@ -7,7 +7,12 @@
xmlns:local="clr-namespace:WebView2Demo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<wv2:WebView2 Name="webView" Source="https://www.bing.com" />
</Grid>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="5">
<TextBox x:Name="msgInput" Width="200" Margin="0,0,5,0" />
<Button Content="发送到 Vue" Click="SendMessage_Click" Padding="10,2" />
</StackPanel>
<wv2:WebView2 Name="webView" />
</DockPanel>
</Window>
+49 -1
View File
@@ -1,4 +1,4 @@
using System.Text;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
@@ -8,6 +8,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.WebView2.Core;
namespace WebView2Demo
{
@@ -19,6 +20,53 @@ namespace WebView2Demo
public MainWindow()
{
InitializeComponent();
InitializeWebView();
}
private async void InitializeWebView()
{
try
{
// 1. 显式初始化
await webView.EnsureCoreWebView2Async(null);
// 2. 注入调试开启指令 (可选)
webView.CoreWebView2.Settings.AreDevToolsEnabled = true;
// 3. 监听消息
webView.WebMessageReceived += WebView_WebMessageReceived;
// 4. 初始化完成后再导航,确保 window.chrome.webview 注入成功
webView.Source = new Uri("http://localhost:5173");
}
catch (Exception ex)
{
MessageBox.Show($"WebView2 初始化失败: {ex.Message}");
}
}
private void WebView_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
// 获取来自前端的消息
string message = e.TryGetWebMessageAsString();
MessageBox.Show($"来自 Vue 的消息: {message}", "WPF 消息中心");
}
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
if (webView.CoreWebView2 != null)
{
string text = msgInput.Text;
if (!string.IsNullOrWhiteSpace(text))
{
// 向前端发送消息
webView.CoreWebView2.PostWebMessageAsString(text);
}
}
else
{
MessageBox.Show("WebView2 尚未就绪,请稍后...");
}
}
}
}
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}
+5
View File
@@ -0,0 +1,5 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>web-app</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+1109
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
{
"name": "web-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.5.25"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.2",
"vite": "^8.0.0-beta.13"
},
"overrides": {
"vite": "^8.0.0-beta.13"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+84
View File
@@ -0,0 +1,84 @@
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const receivedMsg = ref('等待消息...')
const inputMsg = ref('')
const handleMessage = (event) => {
console.log("收到来自 WPF 的消息:", event.data);
receivedMsg.value = event.data
}
onMounted(() => {
if (window.chrome && window.chrome.webview) {
window.chrome.webview.addEventListener('message', handleMessage)
}
})
onUnmounted(() => {
if (window.chrome && window.chrome.webview) {
window.chrome.webview.removeEventListener('message', handleMessage)
}
})
const sendMessageToWPF = () => {
if (window.chrome && window.chrome.webview) {
window.chrome.webview.postMessage(inputMsg.value)
} else {
alert('未在 WebView2 环境中运行')
}
}
</script>
<template>
<div class="container">
<h1>Vue 3 + WebView2 交互演示</h1>
<div class="card">
<h3>接收来自 WPF 的消息:</h3>
<p class="msg-box">{{ receivedMsg }}</p>
</div>
<div class="card">
<h3>发送消息给 WPF:</h3>
<input v-model="inputMsg" placeholder="输入消息" />
<button @click="sendMessageToWPF">发送到 WPF</button>
</div>
</div>
</template>
<style scoped>
.container {
font-family: Arial, sans-serif;
padding: 20px;
text-align: center;
}
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
background: #f9f9f9;
}
.msg-box {
font-weight: bold;
color: #2c3e50;
font-size: 1.2em;
}
input {
padding: 8px;
width: 200px;
margin-right: 10px;
}
button {
padding: 8px 15px;
background-color: #42b883;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #3aa876;
}
</style>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

+43
View File
@@ -0,0 +1,43 @@
<script setup>
import { ref } from 'vue'
defineProps({
msg: String,
})
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
+16
View File
@@ -0,0 +1,16 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 创建 Vue 实例
const app = createApp(App)
// 核心:开发环境强制开启 Vue DevtoolsWebView2 调试必备)
if (import.meta.env.DEV) {
app.config.devtools = true
// 可选:开启性能调试(如需分析性能)
app.config.performance = true
}
// 挂载到 DOM
app.mount('#app')
+79
View File
@@ -0,0 +1,79 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
})