bugfixr
bugfixr

Reputation: 8077

Android - Reading HTML5 localStorage data direct from Java

I've got a simple Android app that has a WebView. The WebView is set to browse to a site which uses JavaScript's localStorage feature.

I've already got my WebSettings set to allow DomStorage:

webSettings.setJavaScriptEnabled(true);
ebSettings.setDomStorageEnabled(true);

String dbPath = this.getApplicationContext().getDir("database", MODE_PRIVATE).getPath();        
webSettings.setDatabasePath(dbPath);

What I need is a way that my Java code can read a variable stored using the localStorage mechanism, ie.:

The JavaScript does this:

    var storage = window.localStorage;
    storage.setItem("name", "Hello World!");

How can I read the value of "name" from localStorage from Java code?

Upvotes: 9

Views: 6051

Answers (4)

Harpreet
Harpreet

Reputation: 3070

To write data :

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
     webView.evaluateJavascript("localStorage.setItem('"+ key +"','"+ val +"');", null);
} else {
     webView.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ val +"');");
}

To read and alert data :

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
     webView.evaluateJavascript("window.alert(localStorage.getItem('"+ key +"'));", null);
} else {
     webView.loadUrl("javascript:window.alert(localStorage.getItem('"+ key +"'));");
}

And remember to enable JavaScript of Android WebvView

webView.getSettings().setJavaScriptEnabled(true);

Upvotes: 0

Savoo
Savoo

Reputation: 963

yes possible to read localStorage value in java (Android).

use this plugin https://www.npmjs.com/package/cordova-plugin-nativestorage that use native storage .

-for that we have to set value in cordova

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

And In Anroid Java File to get this value :

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

Upvotes: 2

in your activity

webView.addJavascriptInterface(myInterface, "JSInterface");

Javascript interface class

class myInterface
{

    @JavascriptInterface
    public void getVariable(string fromLocalStorage)
    {
    //your code
    }

}

in javascript

window.JSInterface.getVariable(localStorage.getItem("variableName"))

Upvotes: 0

Piotr
Piotr

Reputation: 1753

yourWebView.setWebChromeClient(new WebChromeClient(){
      public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        Log.d(tag, "That's my local storage value =" + message);
        return false;
      };
    });
(...)
    yourWebView.loadURL("javascript:alert(localStorage.getItem(\"name\"))");

Upvotes: 0

Related Questions