Created
September 29, 2017 02:28
Star
You must be signed in to star a gist
image adaption in webView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { | |
if webView.canGoBack { | |
// html padding | |
let javascriptString = "document.body.style.padding='0px 12px 0px 12px'; " | |
webView.evaluateJavaScript(javascriptString) { (obj, error) in | |
print(obj) | |
} | |
let imgJs = "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(imgJs, completionHandler: nil) | |
webView.evaluateJavaScript("getImages()", completionHandler: { (obj, error) in | |
if let urls = obj as? String { | |
self.urls = urls.components(separatedBy: "+") | |
print(self.urls) | |
for i in 0..<self.urls.count-1 { | |
// image width | |
webView.evaluateJavaScript("document.getElementsByTagName('img')[\(i)].style.width = '100%';", completionHandler: nil) | |
// click | |
// 无效? | |
let clickJS = "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(clickJS, completionHandler: nil) | |
webView.evaluateJavaScript("registerImageClickAction();", completionHandler: { (obj, error) in | |
print(obj?) | |
}) | |
} | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment