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”);
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裏的代碼:
- @Override
- public 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;
- }
@Override
public 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);
- }
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函數,結果如下: