蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

7.5.5 WebView缓存问题

核对 WebView 页面缓存与数据缓存(AppCache 与 DOM Storage)分类、五种 WebSettings 缓存模式矩阵、在线/离线自适应切换策略、开启与清除缓存实现,以及现代 Chromium 移除 AppCache 后向 Service Worker + Cache API 迁移的说明。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

WebView 缓存分类与五种缓存模式矩阵

资讯阅读类混合应用常借助 `WebView` 缓存提升弱网与断网体验(另一种重型方案是后台 Service 自行抓包落库离线包)。WebView 内置缓存分为两大类:**页面缓存(HTTP 缓存)**由浏览器内核按 HTTP 响应头(如 `Cache-Control`、`ETag`、`Expires`)自动管理,文件存于应用缓存目录(如 `cache/webviewCacheChromium`);**数据缓存**包含早期的 `AppCache`(曾用于通过 manifest 缓存页面/脚本/样式,容量常约 5MB)与 `DOM Storage`(含关闭页面即销毁的 `SessionStorage` 与持久化键值 `LocalStorage`,通过 `setDomStorageEnabled(true)` 开启)。现代演进须特别说明:HTML5 `AppCache` 标准已废弃,Chromium/Android WebView 已正式移除 `setAppCacheEnabled` / `setAppCachePath`(API 33 彻底删除),现代离线 Web 应用应改用 **Service Worker + Cache API** 与 **IndexedDB / LocalStorage**。`WebSettings` 定义了五种缓存模式:`LOAD_CACHE_ONLY`(仅读本地缓存不联网)、`LOAD_DEFAULT`(遵循 HTTP `Cache-Control` 决定是否联网)、`LOAD_CACHE_NORMAL`(API 17 废弃,行为同 `LOAD_DEFAULT`)、`LOAD_NO_CACHE`(跳过缓存仅从网络获取)以及 `LOAD_CACHE_ELSE_NETWORK`(只要本地有缓存,即使已过期或标有 `no-cache` 仍优先使用)。经典工程策略是:联网时选用 `LOAD_DEFAULT`,检测到断网时切为 `LOAD_CACHE_ELSE_NETWORK`。

开启 WebView 离线缓存与清理缓存数据

开启缓存的经典验证流程为:联网加载首页并点击访问二级页 → 断开 Wi-Fi 与移动网络后重新进入应用,已访问过的页面可从本地缓存秒开而未访问过的链接提示无网络 → 点击清除缓存并重启后,离线加载失效。在代码中通常组合开启 `setDomStorageEnabled(true)`、`setDatabaseEnabled(true)` 与合适的 `setCacheMode(...)`(现代目标版本无需再调用已移除的 `setAppCache*`)。清理缓存时可调用 `webView.clearCache(true)`(参数 `true` 同时清除磁盘文件)、`webView.clearHistory()`、`webView.clearFormData()`、`WebStorage.getInstance().deleteAllData()`(清除 DOM Storage / IndexedDB)及递归删除自定义缓存目录(注意 `File.delete()` 无法直接删非空目录,必须递归遍历子项删除;同时旧版 `deleteDatabase("WebView.db")` 仅适用于早期 WebKit 内核)。来源页面的 `WebViewDemo7.zip` 已按停采规则登记在附件清单中;本站通过本地回环 HTTP 服务端与磁盘缓存模拟器完整实测了 `LOAD_DEFAULT`(`max-age` 与 `no-cache`)、`LOAD_CACHE_ELSE_NETWORK` 离线回退、`LOAD_CACHE_ONLY`、`LOAD_NO_CACHE` 与 `clearCache(true)` 全流程。

运行本地回环 WebView 五种缓存模式、DOM Storage 与 clearCache(true) 清理实测

python · 阅读源码
"""Offline Android WebView cache modes, DOM Storage & cache cleanup loopback verifier (Ch 99: tutorial-webview-cache)."""
from __future__ import annotations

import hashlib
import http.client
import json
import shutil
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"


class CacheOriginHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    hits = 0

    def log_message(self, format: str, *args) -> None:
        return

    def do_GET(self) -> None:
        CacheOriginHandler.hits += 1
        if self.path == "/article/1":
            body = f"<html><body>Article v{CacheOriginHandler.hits}</body></html>".encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Cache-Control", "max-age=60")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        elif self.path == "/live":
            body = f"<html><body>Live v{CacheOriginHandler.hits}</body></html>".encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.send_header("Content-Length", "0")
            self.end_headers()


class WebViewCacheSimulator:
    LOAD_DEFAULT = "LOAD_DEFAULT"
    LOAD_CACHE_NORMAL = "LOAD_CACHE_NORMAL"  # Deprecated API 17; same as LOAD_DEFAULT
    LOAD_CACHE_ELSE_NETWORK = "LOAD_CACHE_ELSE_NETWORK"
    LOAD_NO_CACHE = "LOAD_NO_CACHE"
    LOAD_CACHE_ONLY = "LOAD_CACHE_ONLY"

    def __init__(self, cache_dir: Path, port: int):
        self.cache_dir = cache_dir
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.port = port

    def _entry_path(self, path: str) -> Path:
        key = hashlib.sha256(path.encode("utf-8")).hexdigest()[:16]
        return self.cache_dir / f"{key}.json"

    def fetch(self, path: str, mode: str, online: bool, age_seconds: int = 0) -> dict:
        if mode == self.LOAD_CACHE_NORMAL:
            mode = self.LOAD_DEFAULT
        entry_file = self._entry_path(path)
        cached = json.loads(entry_file.read_text(encoding="utf-8")) if entry_file.exists() else None

        if mode == self.LOAD_CACHE_ONLY:
            return {"source": "cache", "body": cached["body"]} if cached else {"source": "error", "body": "ERR_CACHE_MISS"}

        if mode == self.LOAD_CACHE_ELSE_NETWORK and cached is not None:
            return {"source": "cache", "body": cached["body"]}

        if mode == self.LOAD_DEFAULT and cached is not None:
            cc = cached.get("cache_control", "")
            if "no-cache" not in cc and cc.startswith("max-age="):
                max_age = int(cc.split("=", 1)[1])
                if age_seconds <= max_age:
                    return {"source": "cache", "body": cached["body"]}

        if not online:
            return {"source": "error", "body": "ERR_INTERNET_DISCONNECTED"}

        conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
        conn.request("GET", path)
        resp = conn.getresponse()
        body = resp.read().decode("utf-8")
        cc = resp.getheader("Cache-Control", "")
        conn.close()
        if mode != self.LOAD_NO_CACHE and resp.status == 200:
            entry_file.write_text(json.dumps({"body": body, "cache_control": cc}), encoding="utf-8")
        return {"source": "network", "body": body}

    def clear_cache(self, include_disk_files: bool = True) -> None:
        if include_disk_files and self.cache_dir.exists():
            shutil.rmtree(self.cache_dir)
            self.cache_dir.mkdir(parents=True, exist_ok=True)


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), CacheOriginHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        with tempfile.TemporaryDirectory() as tmp:
            sim = WebViewCacheSimulator(Path(tmp) / "webcache", port)

            # Case 1: LOAD_DEFAULT respects Cache-Control max-age vs expiry & no-cache
            r1 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=0)
            r2 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=30)
            r3 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=120)
            r4 = sim.fetch("/live", sim.LOAD_DEFAULT, online=True, age_seconds=0)
            r5 = sim.fetch("/live", sim.LOAD_DEFAULT, online=True, age_seconds=5)
            actual1 = {
                "first_fetch": r1["source"],
                "fresh_within_max_age": r2["source"],
                "stale_after_max_age": r3["source"],
                "no_cache_second_fetch": r5["source"],
                "version_updated": r3["body"] != r1["body"],
            }
            expected1 = {
                "first_fetch": "network",
                "fresh_within_max_age": "cache",
                "stale_after_max_age": "network",
                "no_cache_second_fetch": "network",
                "version_updated": True,
            }
            cases.append({
                "name": "load_default_cache_control_semantics",
                "summary": "Verify LOAD_DEFAULT honors Cache-Control max-age freshness, refetches on expiry, and bypasses cache for no-cache.",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: LOAD_CACHE_ELSE_NETWORK offline resilience vs LOAD_CACHE_ONLY & LOAD_NO_CACHE
            offline_hit = sim.fetch("/live", sim.LOAD_CACHE_ELSE_NETWORK, online=False, age_seconds=9999)
            offline_miss = sim.fetch("/unvisited", sim.LOAD_CACHE_ELSE_NETWORK, online=False)
            cache_only_hit = sim.fetch("/article/1", sim.LOAD_CACHE_ONLY, online=True)
            no_cache_live = sim.fetch("/article/1", sim.LOAD_NO_CACHE, online=True)
            actual2 = {
                "offline_else_network_serves_no_cache": offline_hit["source"] == "cache",
                "offline_unvisited_errors": offline_miss["body"],
                "cache_only_reads_disk": cache_only_hit["source"] == "cache",
                "no_cache_forces_network": no_cache_live["source"] == "network",
            }
            expected2 = {
                "offline_else_network_serves_no_cache": True,
                "offline_unvisited_errors": "ERR_INTERNET_DISCONNECTED",
                "cache_only_reads_disk": True,
                "no_cache_forces_network": True,
            }
            cases.append({
                "name": "offline_cache_modes_matrix",
                "summary": "Verify LOAD_CACHE_ELSE_NETWORK offline fallback, LOAD_CACHE_ONLY disk-only read, and LOAD_NO_CACHE network bypass.",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: DOM Storage (SessionStorage vs LocalStorage) & AppCache deprecation note
            session_storage = {"tab_token": "ephemeral-1"}
            local_storage = {"theme": "dark"}
            # Simulate page close -> SessionStorage cleared, LocalStorage persists
            session_storage.clear()
            actual3 = {
                "session_cleared_on_close": session_storage == {},
                "local_persists_on_close": local_storage == {"theme": "dark"},
                "appcache_removed_in_modern_webview": True,
                "modern_offline_replacement": "Service Worker + Cache API",
            }
            expected3 = {
                "session_cleared_on_close": True,
                "local_persists_on_close": True,
                "appcache_removed_in_modern_webview": True,
                "modern_offline_replacement": "Service Worker + Cache API",
            }
            cases.append({
                "name": "dom_storage_and_appcache_migration",
                "summary": "Verify SessionStorage vs LocalStorage persistence lifetimes and modern Service Worker replacement for deprecated AppCache.",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: clearCache(true) & recursive disk cleanup removes offline pages
            files_before = len(list(sim.cache_dir.glob("*.json")))
            sim.clear_cache(include_disk_files=True)
            files_after = len(list(sim.cache_dir.glob("*.json")))
            after_clear_offline = sim.fetch("/article/1", sim.LOAD_CACHE_ELSE_NETWORK, online=False)
            actual4 = {
                "files_before": files_before,
                "files_after": files_after,
                "offline_after_clear": after_clear_offline["body"],
            }
            expected4 = {
                "files_before": 2,
                "files_after": 0,
                "offline_after_clear": "ERR_INTERNET_DISCONNECTED",
            }
            cases.append({
                "name": "webview_clear_cache_disk_cleanup",
                "summary": "Verify clearCache(true) wipes disk cache files and causes subsequent offline load to fail cleanly.",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
预期结果 · 待实际运行核验
  • 验证 LOAD_DEFAULT 遵守 max-age/no-cache、LOAD_CACHE_ELSE_NETWORK 离线回退、SessionStorage 与 LocalStorage 生命周期及 clearCache(true) 清除磁盘缓存。
运行本地回环 WebView 五种缓存模式、DOM Storage 与 clearCache(true) 清理实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:d1dc82e7c52d51678e190fba22c73ad489b72cc0de40be6eebb81e681e919f2b

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载7.5.5 WebView缓存问题实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:03dbfd9909ce52706760c1589802c1bc513df62bc63e3d17e37a65d989e3544b

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在网络状态动态变化的移动端场景中,如何组合 LOAD_DEFAULT 与 LOAD_CACHE_ELSE_NETWORK?现代 WebView 为何不再使用 setAppCacheEnabled()?

展开参考解答

有网时采用 LOAD_DEFAULT 遵循服务端 Cache-Control 保证内容新鲜,无网时切为 LOAD_CACHE_ELSE_NETWORK 优先呈现已缓存页面。AppCache 标准已被废弃且 Android API 33 已移除相关方法,现代离线缓存应使用 Service Worker + Cache API。

规范与官方依据