相思资源网 Design By www.200059.com
  • Swift 4.0
  • WKWebView

1.注入js代码 (重点)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  let jsGetImages =
    "function getImages(){" +
    "var objs = document.getElementsByTagName(\"img\");" +
    "var imgScr = '';" +
    "for(var i=0;i<objs.length;i++){" +
    "imgScr = imgScr + objs[i].src + '+';" +
    "};" +
    "return imgScr;" +
    "};"
  webView.evaluateJavaScript(jsGetImages, completionHandler: nil)
  webView.evaluateJavaScript("getImages()") { (data, err) in
    let imageUrl:String = data as! String
    var urlArry = imageUrl.components(separatedBy: "+")
    urlArry.removeLast()
    self.imgUrlArray.addObjects(from: urlArry)
    for url in self.imgUrlArray{
      let photo = SKPhoto.photoWithImageURL(url as! String)
      photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache)
      self.images.append(photo)
    }
  }
  var jsClickImage:String
  jsClickImage = 
    "function registerImageClickAction(){" +
    "var imgs=document.getElementsByTagName('img');" +
    "var length=imgs.length;" +
    "for(var i=0;i<length;i++){" +
    "img=imgs[i];" +
    "img.onclick=function(){" +
    "window.location.href='image-preview:'+this.src}" +
    "}" +
    "}"
  webView.evaluateJavaScript(jsClickImage, completionHandler: nil)
  webView.evaluateJavaScript("registerImageClickAction()", completionHandler: nil)
}

2.使用SKPhotoBrowser框架实现图片预览功能

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  let requestString = navigationAction.request.url"image-preview"))!{
    let imgUrl = NSString.init(string: requestString!).substring(from: "image-preview:".count )
    let index = imgUrlArray.index(of: imgUrl)
    let browser = SKPhotoBrowser(photos: images)
    browser.initializePageIndex(index)
    present(browser, animated: true, completion: {})
  }
  decisionHandler(.allow) //一定要加上这句话 
}

总结

以上所述是小编给大家介绍的JS交互点击WKWebView中的图片实现预览效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

标签:
js,点击图片,预览,js,wkwebview

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“JS交互点击WKWebView中的图片实现预览效果”

暂无JS交互点击WKWebView中的图片实现预览效果的评论...