为什么突然要搞这个问题呢?
在开发浏览器的时候遇到这个狗血的问题,花了将近1天的时间才想到这个解决方案,Android与JavaScirpt互调。
因为接口是抓取的别人的,所以出现了JS跨域问题,Android闪亮登场搞定了。
GIF动画演示
WebView相关设置
WebSettings mWebSettings = getSettings();
mWebSettings.setDefaultTextEncodingName("UTF-8");//设置默认的显示编码
mWebSettings.setJavaScriptEnabled(true);//调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
直接放大招->贴代码
Android
1 addJavascriptInterface(new Object() { 2 @JavascriptInterface 3 public void toastMessage(final String url, final int type, final int dir) { 4 L.e("url = " + url + " type = " + type + " dir = " + dir); 5 APIWrapper.getInstance() 6 .getLenovoWord(url) 7 .subscribeOn(Schedulers.io()) 8 .observeOn(AndroidSchedulers.mainThread()) 9 .subscribe(new RxSubscriber<ResponseBody>() { 10 @Override 11 public void _onNext(ResponseBody responseBody) { 12 try { 13 String data = responseBody.string(); 14 L.e("data = " + data); 15 loadUrl("javascript:ResCompleted(" + data + "," + type + "," + dir + ")"); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } 19 } 20 21 @Override 22 public void _onError(String msg) { 23 loadUrl("javascript:ResCompleted(" + msg + ")"); 24 } 25 }); 26 } 27 }, "Android");
Html
1 <html> 2 <meta name="viewport" 3 content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;"> 4 <head> 5 6 <title>Js调用Android代码</title> 7 <style> 8 #button-call{ 9 100%; 10 padding: 20px; 11 font-size: 20px; 12 } 13 #div_bg{ 14 background: #cccccc; 15 margin-top: 50px; 16 } 17 </style> 18 <script type="text/javascript"> 19 window.onload=function() { 20 document.getElementById('button_call').onclick=function(){ 21 window.Android.toastMessage("http://api.sina.cn/sinago/list.json?channel=news_toutiao",1, 0); 22 } 23 } 24 25 function ResCompleted(result,type,dir) { 26 document.getElementById('div_bg').innerHTML='Android调用JS代码-成功!!!'+JSON.stringify(result); 27 } 28 29 </script> 30 </head> 31 32 <body> 33 <button id="button_call">Js调用Android代码</button> 34 <div id="div_bg"></div> 35 </body> 36 37 </html>