检测 Webview 错误并显示消息

Posted

技术标签:

【中文标题】检测 Webview 错误并显示消息【英文标题】:Detecting Webview Error and Show Message 【发布时间】:2011-09-17 13:13:50 【问题描述】:

我想在加载 web 视图页面时显示错误消息(无连接)。这是我目前所拥有的,没有错误处理代码:

public class TrackerPage extends Activity 

    // @Override
    private WebView webview;
    private ProgressDialog progressDialog;

    private boolean error;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

        // Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Set the XML layout
        setContentView(R.layout.tracker_page);

        // Bundle objectbundle = this.getIntent().getExtras();
        webview = (WebView) findViewById(R.id.tracker);

        final Activity activity = this;

        // Enable javascript and lets the browser go back
        webview.getSettings().setJavaScriptEnabled(true);
        webview.canGoBack();

        webview.setWebViewClient(new WebViewClient() 
            public boolean shouldOverrideUrlLoading(WebView view, String url) 
                view.loadUrl(url);
                return true;
            

            public void onLoadResource(WebView view, String url) 
                // Check to see if there is a progress dialog
                if (progressDialog == null) 
                    // If no progress dialog, make one and set message
                    progressDialog = new ProgressDialog(activity);
                    progressDialog.setMessage("Loading please wait...");
                    progressDialog.show();

                    // Hide the webview while loading
                    webview.setEnabled(false);
                
            

            public void onPageFinished(WebView view, String url) 
                // Page is done loading;
                // hide the progress dialog and show the webview
                if (progressDialog.isShowing()) 
                    progressDialog.dismiss();
                    progressDialog = null;
                    webview.setEnabled(true);
                
            

        );

        // The URL that webview is loading
        webview.loadUrl("http://url.org/");
    

我该怎么做?

【问题讨论】:

【参考方案1】:

以上所有答案均已弃用。 您应该在页面完成后使用此代码

 @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
           //Your code to do
        Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error.getDescription(), Toast.LENGTH_LONG).show();
    

【讨论】:

如果您的项目针对 API 级别 @Michael,在 API 级别 1 中引入了另一种具有不同参数的方法 - onReceivedError(WebView, int, String, String) 如果没有互联网,我看到的只是“找不到网页”,并且没有调用这些回调。怎么会?另外,使用 onReceivedError 的更新 API 会更好吗?根据文档,页面上的每个组件都会调用它。当它只针对整个页面时如何检查它? 是否必须同时覆盖两者才能涵盖 api 级别的两种可能性? @MDjava 是的,如果您的目标 API 低于和高于 23,则必须同时覆盖两者。【参考方案2】:

您已经完成了大部分工作...只需实现 onReceivedError 并处理您想要的错误。

【讨论】:

实现这个但不捕获javascript错误只有连接错误等。 对于 javascript 错误,设置一个覆盖 onConsoleMessage() 的 WebChromeClient。【参考方案3】:

在页面完成后添加:

    public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) 
            Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
        

别忘了导入android.widget.Toast;

【讨论】:

【参考方案4】:

根据 API 23 Marshmallow 更新答案

WebViewClient 错误处理

    /*
     * Added in API level 23 replacing :-
     *
     * onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
    */
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request,
            WebResourceError error) 

        Toast.makeText(getActivity(),
                "WebView Error" + error.getDescription(),
                Toast.LENGTH_SHORT).show();

        super.onReceivedError(view, request, error);

    

    /*
      Added in API level 23
    */
    @Override
    public void onReceivedHttpError(WebView view,
            WebResourceRequest request, WebResourceResponse errorResponse) 

        Toast.makeText(getActivity(),
                "WebView Error" + errorResponse.getReasonPhrase(),
                Toast.LENGTH_SHORT).show();


        super.onReceivedHttpError(view, request, errorResponse);
    

网络错误处理

        webView.loadUrl(urlToLoad);

        if (!isConnected(getActivity())) 
            Toast.makeText(getActivity(), "You are offline ", Toast.LENGTH_SHORT).show();

        

     /**
     * Check if there is any connectivity
     * 
     * @param context
     * @return is Device Connected
     */
    public static boolean isConnected(Context context) 

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != cm) 
            NetworkInfo info = cm.getActiveNetworkInfo();

            return (info != null && info.isConnected());
        
        return false;
    

【讨论】:

【参考方案5】:
public class WebClient extends WebViewClient 

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) 
        super.onReceivedError(view, request, error);
        final Uri uri = request.getUrl();
        handleError(view, error.getErrorCode(), error.getDescription().toString(), uri);
    

    @SuppressWarnings("deprecation")
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
        super.onReceivedError(view, errorCode, description, failingUrl);
        final Uri uri = Uri.parse(failingUrl);
        handleError(view, errorCode, description, uri);
    

    private void handleError(WebView view, int errorCode, String description, final Uri uri) 
        final String host = uri.getHost();// e.g. "google.com"
        final String scheme = uri.getScheme();// e.g. "https"
        // TODO: logic
    

【讨论】:

【参考方案6】:

onReceivedError 方法句柄中如下所示

@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description,        String failingUrl) 
    handleError(errorCode,view);


@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) 
    // Redirect to deprecated method, so you can use it in all SDK versions
    onReceivedError(view, rerr.getErrorCode(),rerr.getDescription().toString(),req.getUrl().toString());


HandleError 方法如下

public static void handleError(int errorCode, WebView view) 
    
    String message = null;
    if (errorCode == WebViewClient.ERROR_AUTHENTICATION) 
        message = "User authentication failed on server";
     else if (errorCode == WebViewClient.ERROR_TIMEOUT) 
        message = "The server is taking too much time to communicate. Try again later.";
     else if (errorCode == WebViewClient.ERROR_TOO_MANY_REQUESTS) 
        message = "Too many requests during this load";
     else if (errorCode == WebViewClient.ERROR_UNKNOWN) 
        message = "Generic error";
     else if (errorCode == WebViewClient.ERROR_BAD_URL) 
        message = "Check entered URL..";
     else if (errorCode == WebViewClient.ERROR_CONNECT) 
        message = "Failed to connect to the server";
     else if (errorCode == WebViewClient.ERROR_FAILED_SSL_HANDSHAKE) 
        message = "Failed to perform SSL handshake";
     else if (errorCode == WebViewClient.ERROR_HOST_LOOKUP) 
        message = "Server or proxy hostname lookup failed";
     else if (errorCode == WebViewClient.ERROR_PROXY_AUTHENTICATION) 
        message = "User authentication failed on proxy";
     else if (errorCode == WebViewClient.ERROR_REDIRECT_LOOP) 
        message = "Too many redirects";
     else if (errorCode == WebViewClient.ERROR_UNSUPPORTED_AUTH_SCHEME) 
        message = "Unsupported authentication scheme (not basic or digest)";
     else if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) 
        message = "unsupported scheme";
     else if (errorCode == WebViewClient.ERROR_FILE) 
        message = "Generic file error";
     else if (errorCode == WebViewClient.ERROR_FILE_NOT_FOUND) 
        message = "File not found";
     else if (errorCode == WebViewClient.ERROR_IO) 
        message = "The server failed to communicate. Try again later.";
    
    if (message != null) 
        Toast.makeText(getActivity(), "" + message, Toast.LENGTH_LONG).show();
    

【讨论】:

以上是关于检测 Webview 错误并显示消息的主要内容,如果未能解决你的问题,请参考以下文章

错误消息-> shouldOverrideUrlLoading Webview Android

表单提交后,WebView 未加载页面

Webview 检测 javascript 错误或 url 更改

如何在 Swift 上将 HTML 代码加载到 WebView

如何在android中检测webview或浏览器

Android检测webview URL更改