【问题标题】:Android WebView: Should shouldInterceptRequest be triggered by XmlHttpRequestAndroid WebView:应该由 XmlHttpRequest 触发 shouldInterceptRequest
【发布时间】:2014-09-11 17:15:05
【问题描述】:

我正在尝试集成一个 javascript 插件,该插件通过使用 XmlHttpRequest 调用来加载一些资源。我希望这个脚本在 WebView 的本地加载页面中运行。正如您可能已经猜到的那样,本地资源不允许 XmlHttpRequest 调用,所以我立即收到以下错误:

XMLHttpRequest 无法加载 file:///android_asset/resources.html。叉 源请求仅支持 HTTP。

此时我想我可以通过拦截调用然后自己加载文件来模拟Web服务器,例如:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
        try {
            if (url.contains("resources.html")) { //breakpoint here is not triggering
                return new WebResourceResponse("text/html", "UTF-8", getAssets().open("resources.html"));
            }
        } catch (IOException e) {
            return super.shouldInterceptRequest(view, url);
        }
        return super.shouldInterceptRequest(view, url);
    }
});

问题是shouldInterceptRequest 没有被调用。官方documentation很简短,并没有具体说明拦截什么类型的请求。 This article 有点暗示该方法确实拦截了 XmlHttpRequest 调用,但它似乎不起作用。

有谁知道shouldInterceptRequest 是否应该在XmlHttpRequest 之后调用?如果没有,还有其他方法可以做到这一点吗?谢谢

【问题讨论】:

    标签: android webview xmlhttprequest


    【解决方案1】:

    在 API 级别 16 WebSettings 添加了方法 setAllowFileAccessFromFileURLs() 和 setAllowUniversalAccessFromFileURLs()。将 webView 设置为 true 可能会解决您的问题。

    【讨论】:

    • 有人知道 API
    【解决方案2】:

    作为我对此的测试,似乎只有外部请求会被拦截 - 您可以尝试将本地引用修改为外部为“http://foo.com/...”(而不是“file:///android_asset/ ...”)。

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 2022-11-03
      • 2015-02-17
      • 2015-10-08
      • 2019-09-28
      相关资源
      最近更新 更多