最近遇到关于获取webview加载网页上的点击事件,三种解决方式~~~
一、跟后台协商好,点击该按钮加载特定url,通过webview的代理方法- (BOOL)webView:(UIWebView)webView shouldStartLoadWithRequest:(NSURLRequest)request navigationType:(UIWebViewNavigationType)navigationType 判断加载的url是否是协商好的url;
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url=[NSString stringWithFormat:@"%@",request.URL];
if([url isEqualToString:_urlStr])
{
return NO;
}
return YES;
}
ps:记得要return NO,否则会加载url
二、通过获取所点击按钮的图片来判断是否点击特定位置
1、给webview的scrollview添加手势
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(fakeTapGestureHandler:)];
[tapGestureRecognizer setDelegate:self];
[_webView.scrollView addGestureRecognizer:tapGestureRecognizer];
2、实现UIGestureRecognizerDelegate代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch
{
CGPoint tapPoint = [touch locationInView:_webView];
NSString *script = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", tapPoint.x, tapPoint.y];
NSString *eleIdStr = [_webView stringByEvaluatingJavaScriptFromString:script];
NSLog(@"%@",eleIdStr);
if([eleIdStr isEqualToString:@"按钮的图片url"])
{
//操作
}
return YES;// Return NO to prevent html document from receiving the touch event.
}
document.elementFromPoint 是获取点击坐标的元素
三、通过注入一段JS(需跟web前端协商),返回一段json数据
1、在webview加载完后注入js(具体根据需求定义)
例子:
[_webView stringByEvaluatingJavaScriptFromString:@"var objs = document.getElementsByClassName(\"appShare\");for(var i=0;i<objs.length;i++){var obj = objs[i];obj.href=\"kqapp://{\\\"dataapp\\\":\\\"\" + encodeURIComponent(obj.getAttribute(\"data-app\")) + \"\\\",\\\"appurl\\\":\\\"\" + encodeURIComponent(obj.getAttribute(\"app-url\")) + \"\\\",\\\"apptitle\\\":\\\"\" + encodeURIComponent(obj.getAttribute(\"app-title\")) + \"\\\",\\\"appdescription\\\":\\\"\" + encodeURIComponent(obj.getAttribute(\"app-description\")) + \"\\\",\\\"appimg\\\":\\\"\" + encodeURIComponent(obj.getAttribute(\"app-img\")) + \"\\\"}\";}"];
2、拦截自定义的字段 kqapp://
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@",request.URL.absoluteString);
NSString *urlString = [request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSRange titleRange = [urlString rangeOfString:@"kqapp://"];
if (titleRange.location != NSNotFound) {
urlString = [urlString stringByReplacingOccurrencesOfString:@"kqapp://" withString:@""];//这个urlstring就是一段json字符串
return NO;
}
return YES;
}