0

Is there any way to pass JSONObject from android to javascript. We are using WebView.evaluateJavascript mehtod and are able to send only String type object. In JS if we are checking the method paramter;s typeof(data) then it is displaying as string but in iOS it displays typeof(data) as OBJECT.

In both android and iOS we are passing String and NSString.

JS method is:

   response: function(id, err, data) {
        var dataObj;
        if(typeof(data) == 'string' ){
            dataObj  = JSON.parse(data || '{}');
        }
  }

Android call:

String responseStr = "{\"ok\":\"ok\"}";
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
webView.evaluateJavascript(nativeToWebMethod, null);

2 Answers 2

2

Just send it as if you were loading a url:

private void loadJS(String jsonResponse){

    mWebView.loadUrl("javascript:" + "(function(){" + "yourJsMethodName" + "(" +jsonResponse + ");" + "})()");

}

This will execute a JS Code that will call a function called yourJsMethodName and will pass the JSON as parameter.

Consider execute the last code in the Main Thread

Sign up to request clarification or add additional context in comments.

2 Comments

My code can can already call js method and can send string param to it. Issue is in sending json as an JSONObject.
I don't see your point. Lets say you pass this to your webview -> theFunction( { "ok" : "ok" } );, here you are passing a JSON object, which is different of -> theFunction( "{ \"ok\" : \"ok\"}"); Here you are passing an String. The stuff is in how you construct your responseStr. As you can see you are passing it as 'responseStr', with simple comas. The JS will interprete it as String. But IOS is some times special. It is possible that IOS was interpreting the String directly as JSON
2

I find out the issue, it was in the way I was sending data:

String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";

should be replaced with

String nativeToWebMethod = "javascript:window.nativeService.response("1",'',"+responseStr+")";

removed single quote around the responseStr.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.