Android webview与js 交换JSON对象数据

最近几个项目的测试结果,,Android无法主动通过调用

webview.loadUrl("javascript:"+callbackFunction+"(‘"+data+"’)"); 这种方式将jsonobject类型的data传给js,因为js那边得到就是一个string的对象。

与此同时,js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,例如:

Android 代码:

WebView mWebView = (WebView) this.findViewById(R.id.webview);WebSettings settings = mWebView.getSettings();settings.setJavaScriptEnabled(true);settings.setPluginsEnabled(true);settings.setAllowFileAccess(true);settings.setCacheMode(WebSettings.LOAD_NO_CACHE);mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,会显示白边String url="file:///android_asset/t.html"; //js代码卸载t.html里NavigationInstance navigation =new NavigationInstance(this);mWebView.addJavascriptInterface(navigation, "Navigation");

NavigationInstance里的代码:

@Overridepublic JSONObject GetManeuverInfo() {try{JSONObject test=new JSONObject();test.put("maomao", "value");return test;//return new JSONObject(bean.ManeuverInfo);}catch(Exception e){Log.e(TAG, "",e);}return null;}

t.html里的代码:

function testAPI(el){console.log("———testAPI———");eval("var obj = "+Navigation.GetManeuverInfo());alert(‘typeof:’+typeof(obj));alert(‘maomao:’+obj.maomao);alert(‘obj:’+obj);}

如果直接写成 Navigation.GetManeuverInfo.maomao是会提示undefined,因为js那边只得到了一个string对象而已,它不知道maomao是个key。

通过eval将其转化成表达式就可以调用obj.maomao得到value。

在此ps一下ios,貌似人家支持webview很好,js可以直接获取到json对象.

默认t.html加载会自动执行testAPI函数,结果如下:

影子依旧可以相亲相爱。哪一块骨骼最温暖,总能一击即中。

Android webview与js 交换JSON对象数据

相关文章:

你感兴趣的文章:

标签云: