webview中注入js文件实现js调用本地方法
1.创建一个内部类对象,其中通过@JavascriptInterface来声明android本地方法供js调用;
class JSObject { @JavascriptInterface public void closeWindow() { //do something ... } @JavascriptInterface public void openImage(String img, String url) { //do something ... }}
2.在webview中进行操作
webView.addJavascriptInterface(new JSObject(), "myObj");
3.在WebViewClient()的onPageFinished()方法中注入js代码
String js = "var script = document.createElement('script');"; //常规操作 js+= "script.type = 'text/javascript';"; //常规操作 js+="var child=document.getElementsByClassName(\"btn_back hashover\")[0];"; //根据className来查找对应的组件 js+="child.onclick=function(){userIdClick();};"; //为该组件设置点击事件 js+= "function userIdClick(){myObj.getClose();};"; //通过该点击事件来调用android中的方法// js+= "var ele = document.getElementsByTagName(\"img\");"; js+= "var ele = document.getElementsByClassName(\"strategy_desc\")[0].getElementsByTagName(\"img\");"; js+= "var imgUrl = new String();"; js+= "for (var i = 0; i