美文网首页iOS Developer
WKWebView 实现web的图片点击

WKWebView 实现web的图片点击

作者: LeeDev | 来源:发表于2017-07-20 11:46 被阅读369次

    在web端进行图片点击,就比较简单的往图片标签里面注册一个onclick方法

    1、在didFinish中注册

    //这个是网页加载完成,导航的变化
    -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
        [self addImgClickJS];
    }
    

    2、在加载web端的时候拦截,那里打印的imgPath就是点击的图片

    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
        // 类似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:
        //预览图片
        NSURL * url = navigationAction.request.URL;
        if ([url.scheme isEqualToString:@"image-preview-index"]) {
            //图片点击回调
            NSInteger index = [[url.absoluteString substringFromIndex:[@"image-preview-index:" length]] integerValue];
            NSString * imgPath = self.imageUrlArr.count > index?self.imageUrlArr[index]:nil;
            NSLog(@"imgPath = %@",imgPath);
            decisionHandler(WKNavigationActionPolicyCancel);
        } else {
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }
    

    3、js方法

    - (void)addImgClickJS {
        
        //获取所以的图片标签
        [self.wkWebView evaluateJavaScript:@"function getImages(){\
             var imgs = document.getElementsByTagName('img');\
             var imgScr = '';\
             for(var i=0;i<imgs.length;i++){\
                 if (i == 0){ \
                    imgScr = imgs[i].src; \
                 } else {\
                    imgScr = imgScr +'***'+ imgs[i].src;\
                 } \
             };\
             return imgScr;\
         };" completionHandler:nil];//注入js方法
    
        __weak typeof(self)weakSelf = self;
        [self.wkWebView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            
            if (!error) {
                
                NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil;
                NSLog(@"urlArray = %@",urlArray);
                weakSelf.imageUrlArr = urlArray;
            } else {
                weakSelf.imageUrlArr = nil;
            }
        }];
       
        //添加图片点击的回调
        [self.wkWebView evaluateJavaScript:@"function registerImageClickAction(){\
             var imgs = document.getElementsByTagName('img');\
             for(var i=0;i<imgs.length;i++){\
                 imgs[i].customIndex = i;\
                 imgs[i].onclick=function(){\
                    window.location.href='image-preview-index:'+this.customIndex;\
                 }\
             }\
         }" completionHandler:nil];
        [self.wkWebView evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
    }
    

    相关文章

      网友评论

        本文标题:WKWebView 实现web的图片点击

        本文链接:https://www.haomeiwen.com/subject/qkpdkxtx.html