1. Call the following method in onPageFinished of WebViewClient
private void addImageClickListener(WebView webView) { webView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\"); " + "var imgsxx = new Array(objs.length);" + "for(var i=0;i<objs.length;i++) " + "{" + " imgsxx[i]=objs[i].src;" + " var position=i;" + " objs[i].onclick=function() " + " { " + " window.imageListener.open(imgsxx,this.src); " +//Find the code block labeled img through js code, set the click listener method to connect with the local openImage method " } " + "}" + "})()"); }
2. Define the JS interactive interface MJavascriptInterface
public class MJavascriptInterface { private Activity mActivity; public MJavascriptInterface(Activity activity) { mActivity = activity; } /** * * @param imgs * @param img */ @android.webkit.JavascriptInterface public void open(final String[] imgs, final String img) { } }
3. WebView settings
WebSettings webSettings = getSettings (); webSettings.setUserAgentString (webSettings.getUserAgentString ()); webSettings.setJavaScriptEnabled(true); // Set webview to support JavaScript addJavascriptInterface(new MJavascriptInterface((Activity) getContext()), "imageListener"); webSettings.setJavaScriptCanOpenWindowsAutomatically(true);