【问题标题】:How to handle errors inside webview?如何处理 webview 中的错误?
【发布时间】:2012-12-05 08:10:11
【问题描述】:

我想加载一个网页。

private class MyJavaScriptInterface {

    private MyJavaScriptInterface () {
    }

    public void setHtml(String contentHtml) {

        if (contentHtml != null && contentHtml.trim().length() > 0) {
            //Do something
        }
    }
}
private WebViewClient webViewClient = new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {

        view.loadUrl("javascript:window.ResponseChecker.setHtml"
            + "(document.body.innerHTML);");
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    public void onReceivedSslError(WebView view, SslErrorHandler handler,
        SslError error) {
        handler.proceed();
    }

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Log.e("ProcessPayment", "onReceivedError = " + errorCode);
    }

};

我想处理网页加载错误。我知道错误可以在onReceivedError(...)方法中获取。

我的问题是如何在 webview 中不显示 Page Not found 的情况下处理错误? (例如:显示一个对话框并使 webview 为空白)。

提前致谢。

【问题讨论】:

    标签: android webview webviewclient


    【解决方案1】:

    检查为:

     public void onReceivedError(WebView view, int errorCode, 
                               String description, String failingUrl) {
                 Log.e("ProcessPayment", "onReceivedError = " + errorCode);
    
                //404 : error code for Page Not found
                 if(errorCode==404){
                   // show Alert here for Page Not found
                   view.loadUrl("file:///android_asset/Page_Not_found.html");
                 }
                else{
    
                  }
               }
    

    【讨论】:

    • 我在 onReceivedError 中显示了一个警报。但是 webview 会加载错误页面。
    • @DevuSoman : 在 onReceivedError 发生错误时将 WebView url 设置为您在自定义页面上的 view.loadUrl("file:///android_asset/html_no_copy/Page_Not_found.html"); 试试这个也许可以解决您的问题
    • onReceivedError 不会因 404 而被调用。加载 Web 服务器提供的任何错误文档。此方法仅在网络错误(名称未解析等)时调用。见code.google.com/p/android/issues/detail?id=32755
    【解决方案2】:
    public void onReceivedError(WebView view, int errorCode, String description,
            String failingUrl) {
    
        if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_FILE_NOT_FOUND) {
            // TODO your dialog here
        }
    }
    

    【讨论】:

    • 这是正确答案。 errorCode 来自 WebViewClient 而不是 HTTP 响应
    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    相关资源
    最近更新 更多