【问题标题】:How to detect errors only from the main page in new onReceivedError from WebViewClient如何仅从 WebViewClient 的新 onReceivedError 中的主页检测错误
【发布时间】:2017-05-19 10:49:05
【问题描述】:

上下文

在 Android SDK 23 中,onReceivedError(WebView view, int errorCode, String description, String failingUrl) 已被弃用并替换为 onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)。但是根据documentation

请注意,与已弃用的回调版本不同,新的 版本将被调用任何资源(iframe、图像等),而不仅仅是 主页

问题

我们有一个应用程序,其中在已弃用的 onReceivedError 方法中有一个代码来显示本机视图,而不是让用户在 WebView 中看到错误。

我们想用新方法替换已弃用的onReceivedError 方法。但我们不想显示任何资源的错误的原生视图,只显示主页。

问题

我们如何在新的onReceivedError 中识别错误不是来自主页?

PS 1:我们不希望有像 this 这样的解决方案来存储主 url 并根据失败的 url 检查它。

PS 2:如果解决方案是只使用已弃用的方法,那么新的 Android 版本仍会调用它的保证是什么?

【问题讨论】:

  • 我不确定我的理解是否正确,to store the main url and check it against the failing url.,你为什么不喜欢呢?主页面有变化吗?
  • 是的,它会随着用户浏览网站而改变
  • 明白你的意思,认为主页就像一个网站的主页。您的应用还会针对棒棒糖之前的设备发布吗?
  • 对不起,我之前的不好评论是不必要的 nvm。主 url 可以与资源区分开来吗?意思是页面网址的格式为myurl.com,而图像资源保存在cdn中,格式为cdn.com等...?如果是这样,您可以使用正则表达式并仅过滤主要网址吗?这是假设您在应用程序中显示您的网站...
  • 可能,但我们宁愿不走那条路。之前的 onReceivedError 有一个开箱即用的解决方案,我们想知道是否有一个开箱即用的替代机制

标签: android android-webview webviewclient


【解决方案1】:

WebResourceRequest 具有适用于您的场景的 isForMainFrame() 方法,从 API 版本 21 开始可用:

来源:https://developer.android.com/reference/android/webkit/WebResourceRequest.html

【讨论】:

    【解决方案2】:

    您不必存储原始 URL。您可以从传递给onReceivedError 方法的WebView 获取它。它始终是用户看到的当前页面的完整 URL。因此,您不必担心它们会导航到不同的页面。

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        if (request.getUrl().toString().equals(view.getUrl())) {
            notifyError();
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用like作为代码:

          WebView wv = (WebView) findViewById(R.id.webView);
           wv.setWebViewClient(new WebViewClient() {
              @Override
              public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                      Log.i("WEB_VIEW_TEST", "error code:" + errorCode);
      // here your custom logcat like as share preference or database or static varible.
                      super.onReceivedError(view, errorCode, description, failingUrl);
              }
           });
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多