Access denied using local storage in Android WebView

I have an Android webview that I think has everything you need to access and use localStorage, but when I try to use local storage, I see a "Access Denied" error on the console. Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

Can anyone spot the 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 is 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); 
+6
source share
3 answers

Access to localStorage is only allowed on pages from certain "Web-safe" schemes, such as http: https: and file: It does not work for about: and data: schemes, for example, or for any custom scheme that you could use. Chrome behaves the same, you can check it on the desktop.

+6
source

Did you request storage and network permissions in your .xml manifest?

Something like that:

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+1
source

To manipulate a global object in JS, we need a trick. As @Mikhail Naganov said chrome complains about security Access denied using local storage in Android WebView

I load js as the base url and in js also redirects to the real url. Below code worked for me in 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); 
0
source

Source: https://habr.com/ru/post/986596/


All Articles