6

I have developed a PhoneGap application for Android. The application is composed by the webapp (HTML/jQuery) and a background service (Java code) that's started by the webapp.

This webapp writes to window.localStorage like

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

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

Saxophonist
  • 677
  • 9
  • 16

2 Answers2

8

This is possible. To execute JavaScript and get response you can do as follows:

Define JavaScript callback interface in your 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 your JavaScript calling window.HTMLOUT.someCallback from the script:

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

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

This post here on stackoverflow helped me

You might need to use super.webView.addJavascriptInterface or super.addJavascriptInterface to add the interface. You might need to use super.webView.loadUrl or super.loadUrl to invoke this. It all depends on where you are going to be calling these from.

Community
  • 1
  • 1
Ross
  • 3,335
  • 1
  • 19
  • 18
  • @Ross I know this is an old topic, but could you point me to a repo that has this method fully implemented in a Cordova plugin? I'm trying to modify the Cordova Device plugin to use this code, but I keep getting errors. I know barely any Java. I would love to see a working example of this code. :D – Tyler Buchea Jan 13 '15 at 23:50
  • @user1002379 I'm not aware of any plugins using this approach. Have you seen these SO posts [here](http://stackoverflow.com/questions/2727763/communication-between-android-java-and-phonegap-javascript) and [here](http://stackoverflow.com/questions/14031635/android-4-2-1-webview-and-javascript-interface-breaks?lq=1)? Are you trying to read the values provided by the Cordova device plugin in Java? – Ross Jan 16 '15 at 00:19
  • But webview is not accessible from a Service – oriharel May 20 '15 at 20:32
3

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

it's for IOS,Android Plateform

this plugin use nativeStorage

Cordova 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"));
Savoo
  • 933
  • 7
  • 14