在Android WebView中使用本地存储拒绝访问

bug*_*ixr 10 javascript android webview

我有一个Android webview,我相信它拥有访问和使用localStorage所需的一切,但是,当我尝试使用本地存储时,我在控制台中看到"拒绝访问"错误. Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

谁能发现问题?

JavaScript代码:

function localStorageTest() {
  // Check browser support
  if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    // Retrieve
    document.getElementById("console").innerHTML = localStorage.getItem("lastname");
  } else {
    document.getElementById("console").innerHTML = "Sorry, your browser does not support Web Storage...";
  }
}
Run Code Online (Sandbox Code Playgroud)

这是Android代码:

    // Enable javascript
    WebSettings settings = getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setDatabaseEnabled(true);

    // Create database folder
    String databasePath = getContext().getDir("databases", Context.MODE_PRIVATE).getPath();
    getSettings().setDatabasePath(databasePath);

    getContext().getPackageName() + "/databases/");

    settings.setAppCacheEnabled(true);
    settings.setSaveFormData(true);;
    settings.setLoadWithOverviewMode(true);
    settings.setSaveFormData(true);
Run Code Online (Sandbox Code Playgroud)

Mik*_*nov 8

访问localStorage只允许从某些"网络安全"的方案,如页面http:,https:file:.例如,它不适用于about:data:方案,或者您可能正在使用的任何自定义方案.Chrome的行为方式相同,您可以在桌面上查看.

  • 尝试使用 `WebView.loadDataWithBaseUrl` 并指定一个以 `http:` 方案开头的基本 URL。或者您可以在您的应用程序中运行一个简单的 Web 服务器。 (3认同)

can*_*bax 5

要在JS中操作全局对象,我们需要一个技巧。正如@Mikhail Naganov所说,Chrome抱怨安全性拒绝使用Android WebView中的本地存储访问

我加载js作为基本URL,并且在js中也重定向到真实URL。下面的代码在android 7中为我工作

    String mimeType = "text/html";
    String encoding = "utf-8";
    String injection = "<script type='text/javascript'>localStorage.setItem('key', 'val');window.location.replace('REAL_URL_HERE');</script>";
    webview.loadDataWithBaseURL("REAL_URL_HERE", injection, mimeType, encoding, null);
Run Code Online (Sandbox Code Playgroud)