欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-09-29 08:49:09|栏目:JavaScript代码|点击:
  • 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) //一定要加上这句话 
}

总结

上一篇:Javascript获取图片原始宽度和高度的方法详解

栏    目:JavaScript代码

下一篇:js css3实现图片拖拽效果

本文标题:JS交互点击WKWebView中的图片实现预览效果

本文地址:http://www.codeinn.net/misctech/178076.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有