Android WebView : Should shouldInterceptRequest be triggered by XmlHttpRequest

标签 android webview xmlhttprequest

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

XMLHttpRequest cannot load file:///android_asset/resources.html. Cross origin requests are only supported for 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 调用,但它似乎不起作用。

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

最佳答案

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

关于Android WebView : Should shouldInterceptRequest be triggered by XmlHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688659/

相关文章:

android - robolectric 的一些方法找不到影子方法怎么办?

android - 我怎样才能创建效果隐藏数字信用卡除了最后 3 个数字

android - UserRecoverableAuthException : NeedPermission

android - Webview Android App 中的网站通知

python - 从 wxPython WebView 得到奇怪的结果

php - 如何防止 XMLHttpRequest 在没有 jQuery 的情况下缓存请求?

android - 如何获得网速?

android - Webview 中的 HTML 内容重叠

javascript - 如何使用客户端 JavaScript 在没有框架的情况下从 MongoDB 和 Node.js 服务器查找并返回数据?

node.js - React webapp在PROD环境中不断加载本地主机资源