Android - passing a JSON object from webview javascript to java

I have an Activity with a webview and a javascript interface on the java side. I would like to write a method in Java that can take a json parameter from a web view.

@JavascriptInterface
public String test(Object data) {
    Log.d("TEST", "data = " + data);
}

on my javascript web browser I am calling:

MyAPI.test({ a: 1, b: 2 });

but the data variable is null.

How to pass JSON objects from webview javascript to native method?

thank

+4
source share
2 answers

@ njzk2 is right, do it like this:

In JAVA:

@JavascriptInterface
public String test(String data) {
   Log.d("TEST", "data = " + data);
   return "this is just a test";
}

In JS:

// some code 
var result = test("{ a: 1, b: 2 }");
alert(result);
//some code

function test(args) {
   if (typeof Android != "undefined"){ // check the bridge 
      if (Android.test!= "undefined") { // check the method
         Android.test(args);
      }
   }
}
+1
source

You can use the GSON library or similar to create a Stringified JSON object for Java and JSON.Stringify(data)on the JS side

+1

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


All Articles