WKWebView 实现web的图片点击

在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

你可能感兴趣的:(WKWebView 实现web的图片点击)