Webview AppCache未加载源非HTML内容

时间:2012-06-26 22:54:32

标签: java android html5 html5-appcache

我正在使用HTML5 AppCache创建一个可以离线运行的Android网络应用。使用loadDataWithBaseURL()将附加图像,样式表,javascript和iframe的HTML加载到WebView中。不幸的是,当设备离线时,只有从iframes加载的HTML是从AppCache加载的。

此时,我知道:

  • 此内容确实存在于AppCache中,因为我使用adb shell转储了AppCache.db文件的内容,并在其中找到了所有内容。
  • 这可能不是域问题,因为我在loadDataWithBaseURL()的baseUrl字段中指定了正确的路径。此外,此问题的解决方法成功,没有域错误,如下所述。

这是一些演示代码:

public class ExampleActivity extends Activity {

   ...

  // HTML to be inserted into the Webview with loadDataWithBaseURL()
  public static final String ALL_HTML = 
      "<!DOCTYPE HTML><html>" +
      "<head><script src='sourced_js.js' " +
         "onload='console.log(\"sourced_js.js onload\");'>" +
      "</script>" +
      "<link rel='stylesheet' href='style.css' />" +   // doesn't load offline
      "</head><body>" +
      "<iframe src='manifest.html'></iframe>" +        // loads
      "<img src='android.jpg' />" +                    // doesn't load
      "<img src='android.gif' />" +                    // doesn't load
      "</body></html>";

  public void onCreate(Bundle savedInstanceState) {

    ...

    WebView webView = new WebView(context);
    webView.clearCache(true);

    WebSettings settings = webView.getSettings();
    settings.setAppCacheEnabled(true);
    settings.setJavaScriptEnabled(true);

    webView.loadDataWithBaseURL("http://my.website.com/path/to/content/",
        ALL_HTML, "text/html", "utf-8", null);
  }
}

manifest.html只负责引用清单。它看起来像:

<html manifest="manifest.appcache">
<head></head>
<body></body>
</html>

manifest.appcache看起来像:

CACHE MANIFEST

# Explicitly cached resources
# manifest.html automatically cached
sourced_js.js
android.jpg
android.gif
style.css

NETWORK:
*

在线时,所有内容都会加载。离线时,仅加载manifest.html的iframe。没有加载图片,样式表和javascript。

奇怪的是,如果我在sourced_js.js中获取完全相同的静态内容(android.jpgmanifest.html,...),那么当设备正确地从iframe中的AppCache加载时离线了!好像这些其他资源必须从静态页面中二次获取。

为什么不会从AppCache加载此内容的任何线索?

1 个答案:

答案 0 :(得分:1)

如果您没有根据规范为Web服务器中的* .appcache文件设置正确的MIME类型响应设置(text / cache-manifest),则appcache不起作用。

在桌面浏览器,移动浏览器和iOS UIWebView中也会出现同样的行为。