Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access denied using local storage in Android WebView

I've got an Android webview, that I believe has everything required to access and use localStorage, however, I'm seeing an "Access denied" error in the console when trying to use local storage. Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

Can anyone spot a problem?

JavaScript Code:

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...";
  }
}

Here's the Android code:

    // 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);
like image 816
bugfixr Avatar asked May 05 '15 19:05

bugfixr


People also ask

Does local storage work in WebView?

On Android, LocalStorage works well but only in the current webview. Multiple webviews of the same app can't share the same data with LocalStorage.

What can I use instead of WebView?

Alternatives to WebView If you want to send users to a mobile site, build a progressive web app (PWA). If you want to display third-party web content, send an intent to installed web browsers. If you want to avoid leaving your app to open the browser, or if you want to customize the browser's UI, use Custom Tabs.

How do I turn off local storage?

Type about:config in the address bar to view advanced settings (you may need to click an "Accept the Risk and Continue" button in order to view settings). Search for " dom. storage. enabled ", and double-click on the entry (or use the adjacent toggle button) to toggle its enabled/disabled state.

Is Android WebView deprecated?

This interface was deprecated in API level 12. This interface is now obsolete.


1 Answers

Access to localStorage is only allowed on pages from certain "Web-safe" schemes, like http:, https: and file:. It doesn't work for about: and data: schemes for example, or for any custom scheme you might be using. Chrome behaves the same way, you can check on desktop.

like image 79
Mikhail Naganov Avatar answered Sep 22 '22 08:09

Mikhail Naganov