[IOS]Uiwebview+js交互 之图片点击事件

刚参加工作的时候,在csdn上写过类似的文章,今天维护代码,觉得还是有一点价值的,特来分享一下,大家多拍砖。

111.gif

step1:准备js文件


functionsetImageClickFunction(){

varimgs = document.getElementsByTagName("img");

for(vari=0;i

varsrc = imgs[i].src;

imgs[i].setAttribute("onClick","getImg(src)");

}

document.location = imageurls;}

functiongetImg(src){

varurl=src;

document.location = url;

}

这段js代码的作用是遍历网页源码中“img” 节点,并为每个节点添加一个事件。

- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIWebView*web=[[UIWebViewalloc]initWithFrame:self.view.frame];
[self.viewaddSubview:web];
web.delegate=self;
[webstringByEvaluatingJavaScriptFromString:[NSStringstringWithContentsOfURL:[[NSBundlemainBundle]URLForResource:@"Findimg"withExtension:@"js"]encoding:NSUTF8StringEncodingerror:nil]];
[webloadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.jianshu.com/p/316631f145d6"]]];
}
-(void)webViewDidFinishLoad:(UIWebView*)webView
{
[webViewstringByEvaluatingJavaScriptFromString:@"setImageClickFunction()"];
}
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString*path=[[requestURL]absoluteString];
NSLog(@"%@",path);
if([pathrangeOfString:@"jpg"].location!=NSNotFound)//添加关键字进行是否跳转的筛选
{
ImgShowViewController* img=[[ImgShowViewControlleralloc]init];
img.imgUrl=path;
[selfpresentViewController:imganimated:YEScompletion:nil];
return NO;
}
else
{
return YES;
}
}

让webview加载定义好的js文件 在完成的时候,stringByEvaluatingJavaScriptFromString方法嵌入页面中

最后用于得到uiwebview所有的链接,yes no 决定是否跳转,判断条件可以用jpg,png后缀做判断

这样在Uiwebview中点击图片,会得到图片的url之后就交给你了~~

你可能感兴趣的:([IOS]Uiwebview+js交互 之图片点击事件)