直接主题:Android或iOS webView图片的点击事件处理。
一、Android
1. webView自定义的webViewClient做如下处理
@Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setJavaScriptEnabled(true);
addImageClickListner(view);
}
private void addImageClickListner(WebView contentWebView) {
// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
contentWebView.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\"); " +
"for(var i=0;i<objs.length;i++) " +
"{"
+ " objs[i].onclick=function() " +
" { "
+ " window.android.openImage(this.src); " +
" } " +
"}" +
"})()");
}
其中window.android.openImage(this.src);中的android为自定义标识
2. webView
webView.addJavascriptInterface(new JSInterface(), "android");
其中JSInterface为自定义,android对应webViewClient中的window.android.openImage()
3. JSInterface中代码
public class JSInterface {
public JSInterface() {
}
@JavascriptInterface
public void openImage(String img) {
// img即获取到图片的点击事件,该如何处理自己看着需求。
Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
intent.putExtra((PhotoViewActivity.Intent_PhotoViewActivity_photo, img);
startActivity(intent);
}
}
二、iOS
两个UIWebView代理的使用:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView stringByEvaluatingJavaScriptFromString:@"javascript:(function(){ var objs = document.getElementsByTagName(\"img\"); for(var i=0;i<objs.length;i++) { objs[i].onclick=function() { window.location.href= \"iOS://openImage:/\" + this.src} }})()"];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *urlString = [[request URL] absoluteString];
NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
if([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"iOS"])
{
NSString *funcStr = [urlComps objectAtIndex:1];
if ([funcStr containsString:@"openImage"]) {
NSString *imgSrc = [urlComps objectAtIndex:2];
// imgUrl即为图片地址
NSString *imgUrl = [NSString stringWithFormat:@"http://%@", imgSrc];
}
return NO;
}
return YES;
}
注:两个代理中"iOS"为标识