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

如何阻止Xamarin Forms WebView显示「网页不可用」页面?断网时保留当前页是否可行?

实现Xamarin Forms WebView断网时阻止错误页面并保留当前页面

Absolutely, this is totally doable! You can combine network state monitoring with WebView navigation interception to keep your current page intact and avoid those ugly error screens when the internet drops. Here's a step-by-step guide tailored to your needs:

1. Monitor Network Connectivity in Real-Time

First, you need to track when the network goes offline. Use Xamarin.Essentials.Connectivity (built into Xamarin Forms, no extra packages required) to listen for connectivity changes:

using Xamarin.Essentials;

// In your Page's code-behind
protected override void OnAppearing()
{
    base.OnAppearing();
    Connectivity.ConnectivityChanged += OnConnectivityChanged;
    // Initialize network state on page load
    IsNetworkAvailable = Connectivity.NetworkAccess == NetworkAccess.Internet;
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    Connectivity.ConnectivityChanged -= OnConnectivityChanged;
}

private void OnConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
    IsNetworkAvailable = e.NetworkAccess == NetworkAccess.Internet;
    
    // Optional: Show a friendly offline prompt to users
    if (!IsNetworkAvailable)
    {
        _ = DisplayAlert("Offline", "You've lost internet connection. Your current page will stay as-is.", "Got it");
    }
}

private bool IsNetworkAvailable { get; set; }

2. Block WebView Navigation & Error Pages

Next, you need to stop the WebView from loading error pages when offline. There are two key parts to this:

A. Cancel New Navigation Attempts When Offline

Use the WebView's Navigating event to block any new navigation if there's no network:

<!-- In your XAML, attach the event handler to your WebView -->
<WebView x:Name="AppWebView" Navigating="AppWebView_Navigating" />
// Code-behind handler
private void AppWebView_Navigating(object sender, WebNavigatingEventArgs e)
{
    if (!IsNetworkAvailable)
    {
        e.Cancel = true; // Stop the navigation entirely
        _ = DisplayAlert("Can't Navigate", "No internet connection available. Please check your network settings.", "OK");
    }
}

B. Handle Mid-Load Failures Gracefully

If the network drops while a page is loading, the WebView will trigger the NavigationFailed event. Use this to restore the last valid page instead of showing an error:

<!-- Update XAML to include NavigationFailed and Navigated handlers -->
<WebView x:Name="AppWebView" 
         Navigating="AppWebView_Navigating"
         Navigated="AppWebView_Navigated"
         NavigationFailed="AppWebView_NavigationFailed" />
private string _lastValidUrl; // Track the last successfully loaded page

private void AppWebView_Navigated(object sender, WebNavigatedEventArgs e)
{
    // Save the URL whenever a page loads successfully
    if (e.Result == WebNavigationResult.Success)
    {
        _lastValidUrl = e.Url;
    }
}

private void AppWebView_NavigationFailed(object sender, WebNavigationFailedEventArgs e)
{
    if (!IsNetworkAvailable && !string.IsNullOrEmpty(_lastValidUrl))
    {
        // Reload the last valid page to replace the error state
        ((WebView)sender).Source = new UrlWebViewSource { Url = _lastValidUrl };
        
        // Alternative: Load a custom offline HTML message instead
        // ((WebView)sender).Source = new HtmlWebViewSource { Html = "<div style='text-align:center; margin-top:50px;'><h2>Offline</h2><p>Check your internet connection and try again.</p></div>" };
    }
}

For full control over native error pages (like Android's default "Web page not available" screen), use custom renderers:

Android Custom Renderer

Override OnReceivedError to block native error pages:

using Android.Webkit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))]
namespace YourAppNamespace.Droid.Renderers
{
    public class CustomWebViewRenderer : WebViewRenderer
    {
        public CustomWebViewRenderer(Context context) : base(context) { }

        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                Control.SetWebViewClient(new CustomWebViewClient());
            }
        }

        private class CustomWebViewClient : WebViewClient
        {
            public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
            {
                // Stop loading the error page entirely
                view.StopLoading();
            }
        }
    }
}

iOS Custom Renderer

Override DidFailNavigation to prevent iOS's native error screen:

using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))]
namespace YourAppNamespace.iOS.Renderers
{
    public class CustomWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                Control.NavigationDelegate = new CustomNavigationDelegate();
            }
        }

        private class CustomNavigationDelegate : WKNavigationDelegate
        {
            public override void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error)
            {
                webView.StopLoading(); // Block the native error page
            }
        }
    }
}

Final Tips

  • Initialize _lastValidUrl with your WebView's starting URL so you have a fallback from the get-go.
  • Customize the offline messages/HTML to match your app's branding instead of using generic alerts.
  • The custom renderers add an extra safety net against native error pages that might slip through Xamarin Forms-level events.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:26:38