Android service reading localStorage?

I developed the PhoneGap app for Android. The application is compiled by webapp (HTML / jQuery) and a background service (Java code) launched by webapp.

This webapp writes to window.localStorage , for example

<script> window.localStorage.setItem("name","MyName"); </script> 

Is it possible to read this name that is in localStorage from my Java code?

+6
source share
2 answers

It is possible. To execute JavaScript and get the answer, you can do the following:

Define the JavaScript callback interface in the code:

 class MyJavaScriptInterface { public void someCallback(String jsResult) { // this will be passed the local storage name variable } } 

Attach this callback to your WebView:

 MyJavaScriptInterface javaInterface = new MyJavaScriptInterface(); webView.addJavascriptInterface(javaInterface, "HTMLOUT"); 

Run the JavaScript.HTMLOUT.someCallback call window from the script:

 webView.loadUrl("javascript:( function () { var name = window.localStorage['name']; window.HTMLOUT.someCallback(name); } ) ()"); 

Note. window.localStorage['name'] same as window.localStorage.getItem('name')

fooobar.com/questions/372759 / ...

You may need super.webView.addJavascriptInterface or super.addJavascriptInterface to add an interface. You may need to use super.webView.loadUrl or super.loadUrl to call this. It all depends on where you are going to call.

+8
source

Use the cordova-plugin-nativestorage plugin to read localstorage in the javas android file.

for iOS, Android Plateform

this plugin uses nativeStorage

Cordoba Syntax:

 NativeStorage.setItem("reference", obj, setSuccess, setError); function setSuccess(obj){ } function setError(obj){ } 

Anroid JAVA:

 SharedPreferences sharedPreferences = getSharedPreferences("MainActivity", MODE_PRIVATE); System.out.println("********--------- shared pref values... " + sharedPreferences.getString("myid", "no value")); 
+2
source

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


All Articles