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

Xamarin.Forms HybridWebView的Navigating与Navigated事件不触发问题求助

问题原因与解决方案

1. Navigating/Navigated事件未触发修复

1.1 事件签名不匹配问题

你当前代码中WebOnNavigated方法的参数类型使用错误,Navigated事件对应的参数类型为WebNavigatedEventArgs,你使用了WebNavigatingEventArgs导致事件绑定不匹配,无法触发,直接修正参数即可:

// 修正后的Navigated事件
void WebOnNavigated(object sender, WebNavigatedEventArgs s)
{
    loading.IsVisible = false;
}

1.2 自定义HybridWebView渲染器事件回抛缺失

如果修正签名后事件仍未触发,是因为你使用的自定义HybridWebView在安卓端的渲染器没有将原生WebView的生命周期事件回抛到Forms层。需要修改安卓平台的HybridWebViewRenderer代码,在自定义WebViewClient的对应方法中主动触发事件:

  • 页面开始加载时(对应OnPageStarted方法)调用:
    ((IWebViewController)Element).SendNavigating(new WebNavigatingEventArgs(WebNavigationEvent.NewPage, null, url));
  • 页面加载完成时(对应OnPageFinished方法)调用:
    ((IWebViewController)Element).SendNavigated(new WebNavigatedEventArgs(WebNavigationEvent.NewPage, null, url, WebNavigationResult.Success));
  • 拦截跳转时(对应ShouldOverrideUrlLoading方法)先触发SendNavigating再做拦截逻辑。

2. 外部链接无法唤起系统浏览器修复

该问题本质是Navigating事件未触发导致拦截逻辑未执行,修复事件问题后补充两个适配即可:

2.1 安卓高版本权限适配

安卓API 30及以上版本需要在AndroidManifest.xml的manifest节点下添加 queries 配置,才能正常唤起外部应用:

<queries>
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
</queries>

2.2 API替换

Device.OpenUri已被官方弃用,建议替换为Xamarin.Essentials提供的Launcher.OpenAsync方法,使用时注意添加异步修饰:

// 修改Navigating事件中的跳转逻辑
async void WebOnNavigating(object sender, WebNavigatingEventArgs args)
{
    loading.IsVisible = true;
    if (args.Url.StartsWith("https://mywebsite.com/"))
    {
        return;
    }
    else
    {
        args.Cancel = true;
        await Launcher.OpenAsync(new Uri(args.Url));
    }         
}

额外优化建议

你当前的返回键逻辑没有判断WebView是否可回退,会导致页面退到站点首页后无法正常退出应用,建议修改为:

protected override bool OnBackButtonPressed()
{
    if (webViewElement.CanGoBack)
    {
        webViewElement.GoBack();
        return true;
    }
    return base.OnBackButtonPressed();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:00:03