欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-03 09:36:42
swift 4.0 wkwebview 1.注入js代码 (重点) func webview(_ webview: wkwebview, di...
  • 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?.absolutestring
  print(requeststring!)
  if (requeststring?.hasprefix("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中的图片实现预览效果,希望对大家有所帮助