我正在尝试集成一个 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/