activity代码:
@SuppressLint("SetJavaScriptEnabled")
public class TestInputActivity extends Activity {
WebView contentWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
contentWebView = (WebView) findViewById(R.id.webView);
// 启用javascript
contentWebView.getSettings().setJavaScriptEnabled(true);
// 测试带图的文的网站
contentWebView.loadUrl("http://www.12365auto.com/news/2014-07-10/20140710115457.shtml");
// 添加js交互接口类,并起别名 webtest
contentWebView.addJavascriptInterface(this, "webtest");
contentWebView.setWebViewClient(new MyWebViewClient(this));
}
/**
* 图片点击之后 webview回调的java本地方法,此时拿到了图片地址,君想干嘛就干嘛了!
* 方法名:jsInvokeJava
* @param arg
*/
@JavascriptInterface
public void jsInvokeJava(String img) {
Log.i("songe", "被点击的图片地址为:" + img);
}
MyWebViewClient类
/**
* Created by nicholas on 2018/4/4.
*/
public class MyWebViewClient extends WebViewClient {
private Context con;
public MyWebViewClient(Context con) {
this.con = con;
}
/**
* webview开始加载调用此方法
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.i("songe", "webclient : onPageStarted");
}
/**
* 1-webview 加载完成调用此方法;
* 2-查找页面中所有的<img>标签,然后动态添加onclick事件;
* 3-事件中回调本地java的jsInvokeJava方法;
* 注意:webtest别名和上面contentWebView.addJavascriptInterface(this, "webtest")别名要一致;
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.i("songe", "webclient : onPageFinished");
//动态注入js
view.loadUrl(
"javascript:(function(){"
+ " var objs = document.getElementsByTagName(\"img\"); "
+ " for(var i=0;i<objs.length;i++){"
+ " objs[i].onclick=function(){"
+ " window.webtest.jsInvokeJava(this.src); "
+ " }"
+ " }"
+ "})()");
}
}