Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebView 中 localStorage 無法存取的排查與解法

編輯:關於 Android 程式設計

在 WebView 裡使用 HTML5 的 localStorage,卻發現資料怎麼寫都寫不進去、也讀不出來?這幾乎都是設定沒開對,而不是程式碼有錯。

常見的錯誤嘗試

許多人會這樣設定,但 localStorage 依然無效:

 mainWebView = (WebView)this.findViewById(R.id.mainWebView);
WebSettings settings = mainWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setDatabaseEnabled(true);
String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(dir);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);

真正有效的設定

關鍵是 setDomStorageEnabled(true),再加上 AppCache 相關的設定,localStorage 就會正常運作:

 mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
mWebView.getSettings().setAppCachePath(appCachePath);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAppCacheEnabled(true);

原理說明

HTML5 的離線儲存包含三個不同機制:localStorage/sessionStorage 屬於 DOM Storage,需要 setDomStorageEnabled() 才會生效;Web SQL Database 才需要 setDatabaseEnabled() 與 setDatabasePath();Application Cache 則由 AppCache 那組 API 控制。搞混這三者,設定再多也不會成功。

另外,WebView 的儲存空間預設可能不足,若在裝置設定中關閉了 WebView 的 DOM Storage,一樣會導致寫入失敗,這也是值得檢查的一環。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved