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事件拦截处理:
- XAML中绑定事件:
<WebView x:Name="web_view" Navigating="WebView_Navigating" />
- 后台代码实现事件逻辑:
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
相关产品推荐
相关产品推荐

