Web 视图中个别项目的处理错误

Handling error for individual items in webview

我有一个加载离线 HTML 的网络视图。我的离线 HTML 包含

一切正常,但当用户没有互联网连接时,'text' 和 'images' 加载正常,但 'embedded videos' 部分显示丑陋的无互联网连接错误。

我的问题是如何处理这个错误并将其替换为我自己的自定义错误。

我想继续显示我 html 中的所有其他内容,即使没有互联网连接,但用自定义错误消息替换嵌入的视频错误消息。

有人知道如何实现吗? 干杯

我的网页浏览代码

webView.ClearCache(true);

webView.ClearHistory();

string HTML_DATA = "";

if (File.Exists(localPath))

{

string HTML_LOCAL = File.ReadAllText(localPath);


HTML_DATA =  HTML_LOCAL;

}


webView.Settings.JavaScriptEnabled = true;

webView.Settings.LoadWithOverviewMode = true;

webView.Settings.UseWideViewPort = true;

webView.SetWebViewClient(new WebViewClientClass()); 

webView.LoadDataWithBaseURL("file:///android_asset/", HTML_DATA, "text/html", "UTF-8", null);

现结果如下

With internet

Without internet

My question is how do I handle this error and replace it with my own custom error.

您可以像下面的代码那样在 WebViewClient 中处理它,但它会用您的错误页面替换整个 WebView 页面:

public class MyClient:WebViewClient
{
    public Context _context;
    public MyClient(Context c)
    {
        _context = c;
    }
    public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
    {
        base.OnReceivedError(view, request, error);
        var errMsg = error.DescriptionFormatted;
        Toast.MakeText(_context, errMsg, ToastLength.Long).Show();

        string htmlData = $"<html><body><div align='center'>This is the description for the load fail : {errMsg}</div></body>";

        view.LoadUrl("about:blank");
        view.LoadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
        view.Invalidate();
    }

   ...

或者,您可以在 Html 中处理错误,您可以定义一个与您的 webview 大小相同的错误 window,并根据互联网状态 hide/show 定义它:

<DOCTYPE>
<html>
<head></head>
<body>
        <iframe id="mFrame" width="854" height="480" src="https://www.youtube.com/embed/a5GMRrEJaVo" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
        <div id="errorWindow" width="854" height="480">
            This is the div for your custom error view
        </div>
<script>
    (function(){
        "use strict"

        var mIframe=document.getElementById("mFrame");
        var errorWindow=document.getElementById("errorWindow");

        if(navigator.onLine)
        {
            //internet available
            mIframe.hidden=false;
            errorWindow.hidden=true;
        }else
        {
            //internet not available
            mIframe.hidden=true;
            errorWindow.hidden=false;
        }

    })()
</script>
</body>

注意:您必须定义以下权限才能使 navigator.onLine 工作:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />