You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从.NET Framework 4.5 WebBrowser迁移到WebView2的旧代码更新方法咨询

实现方案

WebView2未提供直接操作DOM的托管API,你需要通过执行JavaScript脚本获取页面元素属性,再将结果返回到.NET层处理,具体实现如下:

第一步:初始化WebView2

首先确保窗体加载时完成WebView2的核心环境初始化:

Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' 初始化WebView2核心运行环境
    Await WebView21.EnsureCoreWebView2Async()
    ' 替换为你的目标页面地址
    WebView21.Source = New Uri("https://你的目标页面地址")
End Sub

第二步:替换原有事件逻辑

原有逻辑在页面导航阶段执行拿不到DOM元素,需要改为在NavigationCompleted事件(页面加载完成后触发)中执行:

Private Async Sub WebView21_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles WebView21.NavigationCompleted
    Try
        ' 导航失败时跳过逻辑
        If Not e.IsSuccess Then Exit Sub

        ' 编写JS脚本获取所需元素属性,返回JSON格式结果
        Dim jsCode As String = "
            JSON.stringify({
                hasBtnDownload: document.getElementById('btnDownload') !== null,
                txtUserValue: document.getElementById('txtUser')?.value || '',
                txtPasswordValue: document.getElementById('txtPassword')?.value || ''
            });
        "
        ' 执行JS并获取返回结果
        Dim jsonResult As String = Await WebView21.ExecuteScriptAsync(jsCode)

        ' 解析JSON结果(此处用System.Text.Json,也可替换为你项目中使用的Newtonsoft.Json)
        Dim jsonRoot = System.Text.Json.JsonDocument.Parse(jsonResult).RootElement

        ' 对应原有btnDownload判断逻辑
        If jsonRoot.GetProperty("hasBtnDownload").GetBoolean() Then
            Application.Restart()
            Environment.Exit(0)
        End If

        ' 对应原有用户名保存逻辑
        Dim userName = jsonRoot.GetProperty("txtUserValue").GetString()
        If Not String.IsNullOrEmpty(userName) Then
            My.Settings.user = userName
        End If

        ' 对应原有密码保存逻辑
        Dim password = jsonRoot.GetProperty("txtPasswordValue").GetString()
        If Not String.IsNullOrEmpty(password) Then
            My.Settings.password = password
        End If

        My.Settings.Save()
    Catch ex As Exception
        ' 按需添加异常处理逻辑
    End Try
End Sub

注意事项

  • 如果你使用的是单页应用(SPA),路由跳转不会触发NavigationCompleted事件,可以改用CoreWebView2.DOMContentLoaded事件触发上述逻辑
  • 若项目未内置System.Text.Json,可通过NuGet安装对应包,或修改解析逻辑适配你当前使用的JSON解析库

内容的提问来源于stack exchange,提问作者Gabriele Cozzolino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:57:02