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

Xamarin Forms中WebView内Href链接点击无效及提取方案咨询

问题背景

在Xamarin Forms项目中,我们使用WebView展示HTML数据,显示HTML内容的代码如下:

var htmlSource = new HtmlWebViewSource();
htmlSource.Html = description;//HTML Content
web_view.Source = htmlSource;

此前通过以下代码解析视频iframe的src链接:

var allMatches = Regex.Matches(description, "<iframe.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);
foreach (Match match in allMatches)
{
    string sourceData = Regex.Match(match.ToString(), "<iframe.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
    vimeoVideoList.Add(sourceData);
}

需求:

  • 参照上述代码解析HTML中的href链接
  • 当前WebView内的href链接点击无响应,若无法修复跳转问题,至少提取href链接列表
解决方案

一、提取href链接列表

使用正则匹配<a>标签的href属性,代码实现如下:

List<string> hrefLinkList = new List<string>();
// 匹配所有带href属性的<a>标签,忽略大小写
var hrefMatches = Regex.Matches(description, "<a.+?href=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);

foreach (Match match in hrefMatches)
{
    string hrefUrl = match.Groups[1].Value;
    // 可选:过滤空链接、锚点链接等无效项
    if (!string.IsNullOrWhiteSpace(hrefUrl) && !hrefUrl.StartsWith("#"))
    {
        hrefLinkList.Add(hrefUrl);
    }
}

说明:正则表达式<a.+?href=[\"'](.+?)[\"'].*?>会捕获所有<a>标签中href的具体值;过滤条件可根据实际业务调整,比如只保留http/https开头的链接。

二、修复WebView href点击无响应问题

Xamarin Forms WebView默认不处理外部链接跳转,需通过Navigating事件拦截处理:

  1. XAML中绑定事件:
<WebView x:Name="web_view" Navigating="WebView_Navigating" />
  1. 后台代码实现事件逻辑:
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
    // 拦截http/https开头的外部链接,用系统浏览器打开
    if (e.Url.StartsWith("http://") || e.Url.StartsWith("https://"))
    {
        e.Cancel = true;
        Device.OpenUri(new Uri(e.Url));
    }
    // 若需WebView内部跳转同一域名链接,移除e.Cancel = true即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:43:09