2013-03-28 71 views
2

我試圖集成一個JavaScript插件,它通過使用XmlHttpRequest調用來加載一些資源。我想讓這個腳本在WebView的本地加載頁面中運行。正如你可能已經猜到了,的XmlHttpRequest呼叫不允許本地資源,所以我及時收到以下錯誤:Android WebView:shouldInterceptRequest是否應該由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調用,但它似乎沒有工作。

有沒有人知道shouldInterceptRequest應該在之後調用XmlHttpRequest?如果沒有,是否有另一種方法來做到這一點?謝謝

回答

2

在API級別16中,WebSettings添加了方法setAllowFileAccessFromFileURLs()和setAllowUniversalAccessFromFileURLs()。將此設置爲true可以解決您的問題。

+0

有沒有人知道API <16的替代方案? – AlvaroSantisteban

0

正如我在這方面的測試,似乎只有外部請求將被攔截 - 您可以嘗試修改本地引用爲「http://foo.com/ ...」(而不是「file:/// android_asset /」。 ..「)。

相關問題