在uiwebview添加手势,解决href含有JS不能调用的问题
2016-04-11 本文已影响277人
韩大发
问题简述
最近在做一个APP,内容主要是HTML5,页面上有这样一段代码,返回以及返回主页的功能键均有js控制,代码如下:
<a href="javascript:nativecall.back();" data-ajax="false" data-icon="back" class="ui-btn-left" data-iconpos="notext"></a> <a href="javascript:nativecall.home();" data-ajax="false" data-icon="home" data-iconpos="notext" class="ui-btn-right"></a>
如果继续使用UIWebViewDelegate中的代理方法如下,不能获取href标签的内容:
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{ }
解决方案
- 首先给uiwebview添加手势,代码如下:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)]; tap.delegate=self; tap.cancelsTouchesInView=NO; [_webaddGestureRecognizer:tap]; NSURLRequest*request = [NSURLRequestrequestWithURL:[NSURLURLWithString:_url]]; [_webloadRequest:request];
- 捕捉手势事件
-(void)handleSingleTap:(UITapGestureRecognizer*)sender { NSLog(@"%s",__func__); CGPointpt = [senderlocationInView:self.web]; NSString*url = [NSStringstringWithFormat:@"document.elementFromPoint(%f, %f).href", pt.x, pt.y]; // href可以换成任意标签获取内容 NSString*urlString = [self.webstringByEvaluatingJavaScriptFromString:url]; NSLog(@"urlString = %@",urlString); if([urlStringcontainsString:@"nativecall.back()"]) { if([_webcanGoBack]) { [_webgoBack]; }else{ [self.navigationControllerpopViewControllerAnimated:YES]; } }else if([urlStringcontainsString:@"nativecall.home()"]){ [self.navigationControllerpopToRootViewControllerAnimated:YES]; } }