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

C# WebView2控件如何获取窗口内用户选中的高亮文本内容

WebView2 控件获取用户选中文本实现方案

WebView2 没有提供直接访问 DOM 对象的托管 API,需要通过执行 JavaScript 脚本的方式获取页面选中内容,实现方式如下:

实现代码

首先在项目中引入 WebView2 相关的 NuGet 包:Microsoft.Web.WebView2。

异步实现(推荐)

using Microsoft.Web.WebView2.Core;
using System.Text.Json;

// 假设你的WebView2控件实例名为 webView21
public async Task<string> GetWebView2SelectedTextAsync()
{
    // 校验WebView2是否已完成初始化
    if (webView21?.CoreWebView2 == null)
    {
        return string.Empty;
    }
    
    // 执行兼容新旧标准的JS脚本获取选中文本,和你之前WebBrowser的逻辑对齐
    string script = """
        (() => {
            if (document.selection) {
                return document.selection.createRange().text || '';
            }
            return window.getSelection().toString() || '';
        })()
        """;
    string jsonResult = await webView21.CoreWebView2.ExecuteScriptAsync(script);
    
    // 反序列化返回的JSON结果,得到纯文本
    return JsonSerializer.Deserialize<string>(jsonResult) ?? string.Empty;
}

同步调用方式

如果需要在非异步方法中调用,可以使用以下方式,注意避免在UI线程直接调用引发死锁:

public string GetWebView2SelectedText()
{
    return GetWebView2SelectedTextAsync().GetAwaiter().GetResult();
}

注意事项

  • 请确保调用该方法前,WebView2 已经完成初始化,可监听CoreWebView2InitializationCompleted事件确认初始化状态
  • 方法返回空字符串包含两种情况:用户未选中任何内容、WebView2 未加载完成或无有效页面内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:09:05